angular - Angular 9:从 ElementRef 获取组件
问题描述
我有适用于表格的指令。它假设在此表单中获取所有组件 MyFormWrapper,并且在表单 submit() 上应该为每个组件调用方法 activate()。由于指令没有视图,我不能使用@ViewChildren 和@ContentChildren。
我的计划是扫描 DOM 树并获取<my-form-element>
. 那部分很容易。我现在缺少的是如何将 ElementRef 转换为 MyFormWrapper 组件实例。知道如何解决这个问题吗?
解决方案
我认为您想将 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;
推荐阅读
- google-apps-script - 使用谷歌脚本将 HTML 电子邮件签名添加到 gsuite 中的所有外发电子邮件
- javascript - 为什么要更改我的轴(moment.js)的时间值?
- sql - 使用 Hive 从字符串中提取带图案的文本
- pentaho - 厨房出口问题:空过滤器真/假标签
- node.js - 在 GET 请求中发送查询参数的最佳实践?
- python - 使用 twitter api 使用 python 发送直接消息
- asp.net-core - Asp.net core 向用户标识多个角色
- boto3 - 调用 boto3.client() 时是否有开销?
- virtual-machine - USRP N210 在使用 GnuRadio 的虚拟机中溢出
- regex - 使用 Wiremock 检查请求正文中的空值