$(document).ready()的Angular等效项是什么?
我想在文档完全加载后执行一次方法(该方法在我的组件内部创建一个组件)。
angular lifecyle hook的任何一个都不起作用(在生命周期的早期阶段未定义this的控制台输出,这意味着未实例化组件/类。在后期,该组件被创建为多次,最终冻结了导航器。)
我已经解决了,所以要回答这个问题:角钩ngAfterViewInit等效于$(document).ready()。
我不说这是唯一的方法,因为它可能取决于您要执行的操作(我是Angular的新手,所以我不确定)。
这里是代码。与在文档准备好之后调用方法相比,它更多地是一种在文档准备好之后创建子组件的方法,因此,大多数方法都超出了问题的范围。
<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>
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);
// ...
}
}