viewChild主要是父組件提取子組件信息的秉溉。廢話不多說泳猬,直接上代碼檩赢。
還是新建幾個指令做測試:
ng g component components/parent
ng g component components/son
viewChild
parent.component.html:
<app-son #son1 uname="jerry"></app-son>
<app-son #son2 uname="tom"></app-son>
<ng-template #test>
<div>這是一個測試</div>
</ng-template>
parent.component.ts:
import { Component, OnInit,ViewChild } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss']
})
export class ParentComponent implements OnInit {
@ViewChild('son1') son:any;
@ViewChild('test') test:any;
constructor() { }
ngOnInit(): void {
}
ngAfterViewInit() {
console.log('子組件的uname:',this.son.uname);//獲取子組件的uname
console.log('ng-template內容:',this.test.elementRef);//獲取ng-template信息
}
}
viewChildren
如果是篩選出多個子組件棕兼,就要用到viewChildren梅掠。
parent.component.ts:
import { Component, OnInit,ViewChildren,QueryList } from '@angular/core';
import { SonComponent } from '../son/son.component'
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.scss']
})
export class ParentComponent implements OnInit {
@ViewChildren(SonComponent) sons:QueryList<SonComponent>;
constructor() { }
ngOnInit(): void {
}
ngAfterViewInit() {
this.sons.forEach(item=>{
console.log(item.uname);
})
}
}
viewChild和contentChild的區(qū)別
viewChild是從父組件提取子組件的信息枢析,而contentChild是從插槽內容中提取組件的信息玉掸。
或者換一種說法,viewChild是提取節(jié)點本身的信息(view)醒叁,而contentChild是提取節(jié)點包裹的內容(content)司浪。