【问题标题】:How to dynamically name element in angular如何以角度动态命名元素
【发布时间】:2021-04-20 09:32:34
【问题描述】:

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

【问题讨论】:

  • 为什么不使用 ViewChildren?你得到一个组件的 QueryList,你可以先得到,传递给数组....

标签: angular viewchild


【解决方案1】:

这也可以在不分配动态模板引用[#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 的所有功能,例如...childNodes[0].innerHTML

【讨论】:

  • 让 comp1: MyCustomComponent = ..childNodes[0].innerHTML;我可以将 .innerHTML 分配给 MyCustomComponent 类类型吗?
  • 你可以,但我不明白你为什么要这样做。
【解决方案2】:

如果您有多个动态创建的组件,您可以通过 ViewChildren 在运行时动态获取其中一个组件

在父组件中:

import { .., ViewChildren,QueryList } from '@angular/core';
...
@ViewChildren(MyComponent) mycomponents!: QueryList<MyComponent>;
// now you can fetch second component by:
this.mycomponents.toArray()[1]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 2018-10-14
    • 2020-08-13
    相关资源
    最近更新 更多