如何在angular中动态命名元素
我想从数组中动态创建组件#cmp1、#cmp2、#cmp3应该是动态的。如何实现这一点如何在angular中动态命名元素,angular,viewchild,Angular,Viewchild,我想从数组中动态创建组件#cmp1、#cmp2、#cmp3应该是动态的。如何实现这一点 <my-component #cmp1></my-component> <my-component #cmp2></my-component> <my-component #cmp3></my-component> componentList: string[] = ['cmp1', 'cmp2', 'cmp3'] 这
<my-component #cmp1></my-component>
<my-component #cmp2></my-component>
<my-component #cmp3></my-component>
componentList: string[] = ['cmp1', 'cmp2', 'cmp3']
这也可以在不指定动态模板引用的情况下实现 在您的.html
<div #container>
<ng-container #main></ng-container>
</div>
这样,您可以评估
ElementRef
的所有功能,如…childNodes[0]。innerHTML
如果您有多个动态创建的组件,则可以在运行时通过ViewChildren动态获取其中一个组件
在父组件中:
import { .., ViewChildren,QueryList } from '@angular/core';
...
@ViewChildren(MyComponent) mycomponents!: QueryList<MyComponent>;
// now you can fetch second component by:
this.mycomponents.toArray()[1]
从'@angular/core'导入{..,ViewChildren,QueryList};
...
@查看儿童(MyComponent)mycomponents!:查询列表;
//现在,您可以通过以下方式获取第二个组件:
this.mycomponents.toArray()[1]
为什么不使用ViewChildren?您将获得组件的查询列表,您可以首先获得,传递到数组….让comp1:MyCustomComponent=…childNodes[0].innerHTML;我可以将.innerHTML分配给MyCustomComponent类类型吗?可以,但我不明白您为什么要这样做。
@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]
import { .., ViewChildren,QueryList } from '@angular/core';
...
@ViewChildren(MyComponent) mycomponents!: QueryList<MyComponent>;
// now you can fetch second component by:
this.mycomponents.toArray()[1]