屬性選擇器,用來從模板視圖上獲取匹配的元素硝训∠煳可以在ngAfterViewInit中獲取到查詢的元素。
格式:
ViewChild(selector:string|Function|Type,opts?:{read?:any;static?:boolean}):any
1:元數(shù)據(jù)屬性
selector:
用于查詢指令類型或名字窖梁。
read:
告訴viewChild返回什么類型的數(shù)據(jù)赘风,取值可以是ElementRef,TemplateRef纵刘,Component邀窃,ViewContainerRef等。
static:
默認(rèn)為false,如果值為false,則是在變更檢測之后解析查詢結(jié)果假哎,值為true瞬捕,是在變更檢測之前解析。
2:常見用法
1:同一個(gè)組件舵抹,一般不直接使用原生方法操作dom,可以借助viewChild:
<div #divDemo>abc</div>
@ViewChild('divDemo',{read:ElementRef}) divDemo!:ElementRef;
ngAfterViewInit(){
divDemo.nativeElement.style.color = 'red';
}
2:父子組件肪虎,當(dāng)我們需要獲取子組件的值和方法的時(shí)候
有兩種形式:一種是使用放置錨點(diǎn)的方法,一種是引入子組件掏父。
2.1:放置錨點(diǎn)
//子組件test-child.ts
title='初始化的title值';
changeTitle():void {
this.title = '改變了title';
}
//父組件app.html
<app-test-child #testChild></app-test-child>
<button (click)="changeChildTitle()">改變子組件的title值</button>
//父組件app.ts
@ViewChild('testChild')testChild!:any;
changeChildTitle():void {
this.testChild.changeTitle();
}
2.2:引入子組件
import { TestChildComponent } from './test-child/test-child.component';
@ViewChild(TestChildComponent) testChild!:TestChildComponent;
3:問題
報(bào)ExpressionChangedAfterItHasBeenCheckedError錯(cuò)誤,需要設(shè)置static:true
//父組件
<p>{{testChild.title}}</p>
//報(bào)錯(cuò)
//ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '[object Object]'..
{ static: true } 其實(shí)就是靜態(tài)查詢,在ngOnInit中可用笋轨。
{ static:false } 其實(shí)就是動態(tài)查詢,一般結(jié)合*ngIf使用赊淑。
viewChildren和viewChild類似,但沒有static選項(xiàng)爵政。
返回一個(gè)QueryList集合。
<div #divDemo>123</div>
<div #divDemo>456</div>
@ViewChildren ('divDemo') divDemo!:QueryList<ElementRef>;
ngAfterViewInit(){
this.divDemo.forEach(ele=>{
console.log(ele);
})
}