admin 管理员组

文章数量: 1184232

1. 通过@ViewChild获取子组件,得到子组件的值、调用子组件的方法

//子组件child
@Component({
  selector: 'app-child',
  templateUrl: './childponent.html',
  styleUrls: ['./childponent.scss']
})
export  class Child{
	public content:string = '123'
	public change(){
		this.content = 'aa'
	}	
}
//父组件parent
<app-child  #Children></app-child>


import { ViewChild } from '@angular/core';
@Component({
  selector: 'app-parent',
  templateUrl: './parentponent.html',
  styleUrls: ['./parentponent.scss']
})
export  class Parent{
    //通过@ViewChild获取子组件,得到子组件的值、调用子组件的方法
	@ViewChild('Children', { static: true }) children: any;
	public show():void{
		//获取子组件的属性以及方法
		console.log(this.children.content)
		this.children.change();
	}	
}

2.通过@ViewChild获取某个元素

<p #dom>1111</p>
<button (click)="changeColor()">changeColor</button>


@ViewChild('dom', { static: true }) eleRef:ElementRef;
public changeColor():void{
	this.eleRef.nativeElement.style.color = 'red'; 
}	

对于static,意思就是:如果为true,则在运行更改检测之前解析查询结果,如果为false,则在更改检测之后解析。默认false.
怎么理解呢?
主要就在于“更改检测”这个动作的发生节点。
例如,我们经常使用到的ngIf、ngShow指令,如果子组件中加入了这些指令,而同时static为true。那么,当我们去捕获指代目标时,得到的值将是undefined

这块可能会报错:Property ‘eleRef’ has no initializer and is not definitely assigned in the constructor.
解决:

  • 方法一:在tsconfig.json配置以下设置
"compilerOptions": {
	//严格属性初始化
	"strictPropertyInitialization": false,
}
  • 方法二:使用非空断言符合!
@ViewChild('dom', { static: true }) eleRef!:ElementRef;

本文标签: Angular ViewChild