首页 > 解决方案 > Angular 9:从 ElementRef 获取组件

问题描述

我有适用于表格的指令。它假设在此表单中获取所有组件 MyFormWrapper,并且在表单 submit() 上应该为每个组件调用方法 activate()。由于指令没有视图,我不能使用@ViewChildren 和@ContentChildren。

我的计划是扫描 DOM 树并获取<my-form-element>. 那部分很容易。我现在缺少的是如何将 ElementRef 转换为 MyFormWrapper 组件实例。知道如何解决这个问题吗?

标签: angularcomponentsdirective

解决方案


我认为您想将 ElementRef 升级为 ComponentRef。

我认为这段代码是你需要的:

// constructor services
private readonly renderer: Renderer2,
private readonly resolver: ComponentFactoryResolver,
private readonly injector: Injector,
private readonly app: ApplicationRef

// Generation
const factorySpinner: ComponentFactory<MatSpinner> = this.resolver.resolveComponentFactory(MatSpinner);
const refSpinner: ComponentRef<MatSpinner> = factorySpinner.create(this.injector);
this.app.attachView(refSpinner.hostView);
refSpinner.instance.color = "accent";
refSpinner.instance.diameter = 24;
const elSpinner: ElementRef<MatSpinner> = refSpinner.location;
const oSpinner: MatSpinner = elSpinner.nativeElement;

推荐阅读