在组件中,我有两个指令:
@Directive({
selector: '[ng-parent]'
})
export class Parent implements OnInit, AfterViewInit {
public ngOnInit(): void {
console.log('parent.directive:ngOnInit');
}
ngAfterViewInit() {
console.log('parent.directive:ngAfterViewInit');
}
}
@Directive({
selector: '[ng-child]'
})
export class Child implements OnInit, AfterViewInit {
public ngOnInit(): void {
console.log('child.directive:ngOnInit');
}
ngAfterViewInit() {
console.log('child.directive:ngAfterViewInit');
}
}
在main.component
上,我使用如下指令:
<div ngParent>
<ng-template ngFor let-row [ngForOf]="arrRows">
<div>
<ng-template ngFor let-field [ngForOf]="arrFields">
<div ngChild></div>
</ng-template>
</div>
</ng-template>
</div>
控制台显示结果初始化顺序:
main.component:ngOnInit
ng-parent.directive:ngOnInit
ng-parent.directive:ngAfterViewInit
main.component:ngAfterViewInit
ng-child.directive:ngOnInit
ng-child.directive:ngAfterViewInit
我简化了代码。我猜问题是ng-template
中的ng-template
。据我了解,生命周期顺序应该有所不同。我需要结果初始化生命周期
指令序列如下:
main.component:ngOnInit
ng-parent.directive:ngOnInit
ng-child.directive:ngOnInit
ng-child.directive:ngAfterViewInit
ng-parent.directive:ngAfterViewInit
main.component:ngAfterViewInit