1.创建一个Output()事件,在父组件上触发该事件,然后在子组件中监听该事件。
父组件模板:
父组件组件类:
export class ParentComponent {
// 父组件逻辑...
onTemplateChange() {
// 在模板更改后执行操作
}
}
子组件组件类:
export class ChildComponent {
@Output() templateChanged = new EventEmitter();
ngAfterViewInit() {
this.templateChanged.emit();
}
}
当子组件的视图加载完成后,它会触发父组件上的Output()事件,父组件会收到该事件并执行其句柄中的方法。
2.使用ViewChild()获取子组件引用,并在父组件的AfterViewInit()生命周期中调用该方法。
父组件组件类:
import {AfterViewInit, Component, ViewChild} from '@angular/core';
import {ChildComponent} from './child.component';
export class ParentComponent implements AfterViewInit {
@ViewChild(ChildComponent) childComponent: ChildComponent;
ngAfterViewInit() {
this.childComponent.callMethod();
}
}
子组件组件类:
export class ChildComponent {
callMethod() {
// 子组件中调用的方法
}
}
在父组件的生命周期中,使用ViewChild()获取子组件的引用,并在AfterViewInit()期间调用该方法。注意,子组件必须在此期间正确加载才能使用此方法。