解决您的疑问-
Parent-
<app-child></app-child>
@ViewChild('child') child: ChildComponent;
ngAfterViewInit() {
// When accessing with ViewChild(), use this lifecycle hook
// to call methods or for anything related to that component
this.child.show();
}
Child-
show(){
console.log('HELLO WORLD');
}
有关访问子组件的额外信息 -
有 3 种方法可以通过角度查询子组件、组件的子项或 Html DOM 元素,并且您可以获取查询的 DOM 或组件的对象的最早可能时刻是在ngAfterViewInit
生命周期钩子中。
1.)根据组件名称查询
app.component.ts
@ViewChild('cardRef', {read: ElementRef}) card1: ElementRef; //by this you can achieve querying over HTML DOM objects
@ViewChild('container') containerDiv: ElementRef;
ngAfterViewInit() {
console.log("cardRef = ", this.card1);
console.log("container = ", this.containerDiv);
}
app.component.html
<div class="product" #container>
<product-card #cardRef></product-card>
</div>
2.)根据参考查询。当您有多张卡片带有不同的数据集并且想要操作其中任何一张时,这很有用。
app.component.ts
@ViewChild('cardRef1') card1: ProductCardComponent;
@ViewChild('cardRef2') card2: ProductCardComponent;
ngAfterViewInit() {
console.log("cardRef1 = ", this.card1);
console.log("cardRef2 = ", this.card2);
}
app.component.html
<div class="product">
<product-card #cardRef1 [course]="course[0]"></product-card>
<product-card #cardRef2 [course]="course[1]"></product-card>
</div>
3.)当您对集合列表进行查询时,您可以使用@ViewChildren()装饰器。
app.component.ts
@ViewChildren(ProductCardComponent) cards: QueryList<ProductCardComponent>; //QueryList will give a lot methods embedded in it (e.g. first, last, forEach, etc)
ngAfterViewInit() {
console.log(this.cards.first); //It will give the object for the first card
}
app.component.html
<div class="product" #container>
<product-card *ngFor="let product of products"></product-card>
</div>
我希望这能消除你的疑问。