angular-viewChild和viewChildren
2020-11-26 本文已影响0人
姜治宇
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的区别
viewChild是从父组件提取子组件的信息,而contentChild是从插槽内容中提取组件的信息。
或者换一种说法,viewChild是提取节点本身的信息(view),而contentChild是提取节点包裹的内容(content)。