繁体   English   中英

要在DOM中查找元素而不使用在angular 2+中使用* ngFor生成的document.getElementById()

[英]To find the element in DOM without using document.getElementById() generated using *ngFor in angular 2+

app.component.html:

<div *ngFor = "let ivalue of arraytoDispaly;let i = index;">
      <input type="text" id={{i}} [value]="ivalue.inputValue" />
</div>
<button (click)='GetElementValue()'>GetElementValue</button>

app.component.ts:

arraytoDispaly = [{'inputValue':'abc'},
                  {'inputValue':'def'},
                  {'inputValue':'ghi'}];
GetElementValue(){
 var t = (<HTMLInputElement>document.getElementById('1')).value;
 console.log(t);
}

每当我单击“ GetElementValue”按钮时,我都会获得ID为“ 1”的输入字段的值作为“ def”。 需要知道还有其他方法可以访问* ngFor生成的angular元素。 谢谢

使用模板变量标记您的输入:

<div *ngFor = "let ivalue of arraytoDispaly;let i = index;">
      <input #inputs type="text" id={{i}} [value]="ivalue.inputValue" />
</div>
<button (click)='GetElementValue()'>GetElementValue</button>

然后,您可以使用@ViewChildren并使用QueryList API查询QueryList

@ViewChildren('inputs', 
    { read: ElementRef }) inputs: QueryList<ElementRef>;

可能的read值是: ElementRefViewContainerRef或Component / Directive本身的名称(如果在一个元素上有多个指令,则很有用)。

如果需要,可以通过实现AfterViewInit来初始化元素:

ngAfterViewInit(): void {
   // so something with inputs
}

您还可以通过点击处理程序访问inputs

GetElementValue(){
   var t = (<HTMLInputElement> this.inputs.toArray()[1].nativeElement).value;
   console.log(t);
}

或更简洁地使用map

 GetElementValue(){
    var t = (<HTMLInputElement> this.inputs.map(t=>t.nativeElement)[1]).value;
    console.log(t);
 }

有关更多信息,这是有关如何使用@ViewChildren的所有信息:

https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e

https://blog.angular-university.io/angular-viewchild/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM