首页 > 解决方案 > 如何以角度动态命名元素

问题描述

我想从数组动态创建组件。#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)

标签: angularviewchild

解决方案


这也可以在不分配动态模板引用的情况下实现[#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]

像这样你可以评估ElementReflike的所有功能...childNodes[0].innerHTML


推荐阅读