当一个指令位于Angular 6中的另一个指令内时,工作指令的生命周期顺序如何?

时间:2018-09-21 17:15:43

标签: angular angular6

在组件中,我有两个指令:

@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

0 个答案:

没有答案