[英]How to know WHEN a dynamically created Angular component is available to request in the DOM?
我像這樣動態創建一個 Angular 組件(代碼被簡化,有一些缺失的部分):
[...]
@ViewChild(MyDirective, { static: true }) myHost!: MyDirective;
constructor(
private readonly compiler: Compiler,
private readonly injector: Injector,
) {}
[...]
const myModule: typeof MyModule = (
await import('../../../my/my.module')
).MyModule;
const moduleFactory: NgModuleFactory<MyModule> = await this.compiler.compileModuleAsync(
myModule,
);
const moduleReference: NgModuleRef<MyModule> = moduleFactory.create(this.injector);
const componentFactory: ComponentFactory<MyComponent> = moduleReference.instance.resolveComponent();
const componentReference: ComponentRef<MyComponent> = myHost.viewContainerReference.createComponent(
componentFactory,
undefined,
moduleReference.injector,
);
componentReference.instance.item = myItem;
componentReference.instance.options = myOptions;
// Here I need to wait ~200ms for the component to be available to request in the DOM ...
await timer(200).toPromise();
const myComponent: Element = document.querySelector('my-component');
// Then I use the component to generate an image with the library html-to-image
const dataUrl: string = await toSvg(myComponent);
return dataUrl;
我必須等待大約 200 毫秒才能讓我的組件在 DOM 中可用以請求......否則它返回未定義。 我試圖在MyComponent
中實現ngAfterViewInit
,然后公開一個 observable,以便我可以訂閱它然后請求它,但它仍然返回未定義。 MyComponent
只有@Inputs 和一個模板,沒有別的。 模板看起來像這樣:
<ng-container *ngIf="condition; else loading">
<div prop="stuff | MyPipe">stuff</div>
</ng-container>
<ng-template #loading>
stuff
</ng-template>
我如何知道動態創建的組件何時可供請求?
我不知道我是否正確理解了您的代碼,因為有一些缺失的部分。 我認為 MyDirective 是您的錨指令。 下面的答案是基於我對您的代碼庫的理解所做的那些假設。
您應該使用 ComponentFactoryResolver.resolveComponentFactory() 為每個組件解析 ComponentFactory。
const componentFactory = this.componentFactoryResolver.resolveComponentFactory("give component name here");
const viewContainerRef = this.directiveName.viewContainerRef; //the directive should inject viewContainerRef to access the view container of the parent component which will host the dynamic components
viewContainerRef.clear();
const componentRef = viewContainerRef.createComponent<DynamicComponent>(componentFactory);
在此處閱讀有關此內容的更多信息https://angular.io/guide/dynamic-component-loader
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.