angular - 如何以角度动态命名元素
问题描述
我想从数组动态创建组件。#cmp1,#cmp2,#cmp3应该是动态的怎么实现
<my-component #cmp1></my-component>
<my-component #cmp2></my-component>
<my-component #cmp3></my-component>
componentList: string[] = ['cmp1', 'cmp2', 'cmp3']
而且我必须在运行时根据字符串值动态获取这些组件
let reqiuredComponent = 'cmp2'
let captureComponent: MyComponent = @ViewChild(requiredComponent)
解决方案
这也可以在不分配动态模板引用的情况下实现[#cp1, #cp2 ...]
。
在你的.html
<div #container>
<ng-container #main></ng-container>
</div>
在你的.ts
@ViewChild('main', {read: ViewContainerRef}) vcr: ViewContainerRef;
@ViewChild('container') container: ElementRef;
constructor(private cfr: ComponentFactoryResolver,
private el: ElementRef) {}
ngAfterViewInit() {
for(let i=0; i<3; i++) {
this.vcr.createComponent(this.cfr.resolveComponentFactory(MyComponent));
}
}
现在访问您的不同组件
console.log(this.container.nativeElement.childNodes[1] //childNodes[0|1|2]
像这样你可以评估ElementRef
like的所有功能...childNodes[0].innerHTML
推荐阅读
- bash - VSCode 打开工作区时如何运行 bash 命令或设置环境变量
- spring-cloud-gateway - Retry GatewayFilter 在 Spring Cloud Gateway 上无法按预期工作
- flutter - 屏幕加载时如何仅调用一次 bloc 事件
- pdf - 如何为 pandoc 中的代码块添加边框?
- python - 如何仅通过所有索引中的 id 从 elasticsearch 获取文档
- powershell - 使用带有密码授予类型的 Graph API 和 Powershell 的联合 ID
- google-apps-script - 将每行中的值从一个单元格复制到另一个单元格,作为 Google 工作表中的“值”
- python - 如何将具有相同缺失列的列与熊猫合并
- javascript - 使用 Formik 编辑条目,Yup 无法识别现有字段
- javascript - 如何在 yaml 脚本中获取 curl 响应 JSON?