框架: Angular 2 Typescript
要引用的组件 ng2-select
模板:
<div *ngFor="let item of items; let **i=index**;>
<ng-select [items]="myItems" #element**{{i}}**><ng-select>
</div>
打字稿:
如果是单个元素
@ViewChild('element') select:SelectComponent;
以后
this.select.active = [{id:0,text:'Africa'}] //正常但我想像下面的函数一样使用它
但我想要
在功能块中,我想引用选定的动态#element 否并更改值 例如
myFunction(i:number){
//Change active attribute of the corresponding element dynamically referenced from DOM using View Child / Renderer / Element Ref or anything that might help
}
请帮助我!
答案 0 :(得分:0)
<强>更新强>
@ViewChild()
不支持动态参数。你可以注入
constructor(private elRef:ElementRef) {}
然后使用
myFunction(i:number) {
this.elRef.nativeElement.querySelector('[' + i ']');
}
提示:属性名称不能以数字AFAIR开头。
<强>原始强>
myFunction(i:number) {
this.select.setAttribute('id', i);
this.select.setAttribute('text', 'Aftrika');
}