Angular 9 - 相当于 $(document).ready()

Angular 9 - Equivalent of $(document).ready()

$(document).ready() 的 Angular 等价物是什么?

我想在文档完全加载时执行一次方法(该方法在我的组件中创建一个组件)。

angular lifecyle hook

None 正在工作(控制台输出 this 在生命周期的早期阶段未定义,这意味着 component/class没有实例化,后期组件创建次数多,导致navigator卡死。)

我解决了,所以回答这个问题:angular hook ngAfterViewInit 相当于 $(document).ready()

我并不是说这是唯一的方法,因为它可能取决于你想做什么(我是 Angular 的新手,所以我可以不确定)。

这是代码。它更多的是关于文档准备好后创建子组件的方法,而不是文档准备好后调用方法,所以大部分都超出了问题的范围。


HTML

<div>
    <!-- Template that can contain multiple components of any kind. 
         I want it to contain a 'ComponentA' before the page is rendered. -->
    <template #containerForChildrenComponents></template>
</div>

TypeSript

export class MainComponent implements AfterViewInit {

    @ViewChild('containerForChildrenComponents', {read: ViewContainerRef}) entry: ViewContainerRef;

    constructor(private readonly resolver: ComponentFactoryResolver,
                private readonly changeDetectorRef: ChangeDetectorRef) {
    }

    ngAfterViewInit(): void {
        // Call the method creating a child component of class 'ComponentA' inside the template
        this.createChildComponentA();
        this.changeDetectorRef.detectChanges();
    }

    createChildComponentA() {
        const factory = this.resolver.resolveComponentFactory(ComponentA);
        const componentRef = this.entry.createComponent(factory);
        // ...
    }
}