[英]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.