如何知道动态创建的Angular组件何时可以在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中使用我的组件来请求。。。否则返回undefined。我曾尝试在MyComponent中实现ngAfterViewInit,然后公开一个可观察对象,这样我就可以订阅它并请求它,但它仍然返回未定义的结果。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

最新更新