0

我像这样动态创建一个 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 中可用以请求……否则它返回未定义。我试图实现ngAfterViewInitMyComponent然后公开一个可观察的,以便我可以订阅它然后请求它,但它仍然返回未定义。MyComponent只有@Inputs 和一个模板,没有别的。模板看起来像这样:

<ng-container *ngIf="condition; else loading">
  <div prop="stuff | MyPipe">stuff</div>
</ng-container>

<ng-template #loading>
  stuff
</ng-template>

我如何知道动态创建的组件何时可供请求?

4

1 回答 1

0

I don't know if I have understood your code properly as there are some missing pieces. I think MyDirective is your anchor directive. And the answer below is based on those assumptions that I have made based on my understanding of your code base.

You should be using ComponentFactoryResolver.resolveComponentFactory() to resolve ComponentFactory for each of the components.

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);

Read more about this here https://angular.io/guide/dynamic-component-loader

于 2021-06-07T10:26:29.447 回答