我像这样动态创建一个 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 中可用以请求……否则它返回未定义。我试图实现ngAfterViewInit
,MyComponent
然后公开一个可观察的,以便我可以订阅它然后请求它,但它仍然返回未定义。MyComponent
只有@Inputs 和一个模板,没有别的。模板看起来像这样:
<ng-container *ngIf="condition; else loading">
<div prop="stuff | MyPipe">stuff</div>
</ng-container>
<ng-template #loading>
stuff
</ng-template>
我如何知道动态创建的组件何时可供请求?