简体   繁体   English

Angular 9:从 ElementRef 获取组件

[英]Angular 9: get Component from ElementRef

I have Directive that I would apply to the form.我有适用于表格的指令。 It suppose to get all components MyFormWrapper inside this form and on form submit() should call method activate() for each.它假设在此表单中获取所有组件 MyFormWrapper,并且在表单 submit() 上应该为每个组件调用方法 activate()。 Since Directive doesn't have view I can not use @ViewChildren and @ContentChildren.由于指令没有视图,我不能使用@ViewChildren 和@ContentChildren。

My plan is to scan through DOM tree and get ElementRefs of the <my-form-element> .我的计划是扫描 DOM 树并获取<my-form-element> ElementRefs。 That part is easy.那部分很容易。 What I am missing now is how to convert ElementRef into MyFormWrapper component instance.我现在缺少的是如何将 ElementRef 转换为 MyFormWrapper 组件实例。 Any idea how to solve this problem?知道如何解决这个问题吗?

I think you want to upgrade a ElementRef to a ComponentRef.我认为您想将 ElementRef 升级为 ComponentRef。

I think this code backward is what you need:我认为这段代码是你需要的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM