[英]To find the element in DOM without using document.getElementById() generated using *ngFor in angular 2+
app.component.html: 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: app.component.ts:
arraytoDispaly = [{'inputValue':'abc'},
{'inputValue':'def'},
{'inputValue':'ghi'}];
GetElementValue(){
var t = (<HTMLInputElement>document.getElementById('1')).value;
console.log(t);
}
Whenever I am clicking on 'GetElementValue' button, I am getting the value of input field with id of '1' as 'def'. 每当我单击“ GetElementValue”按钮时,我都会获得ID为“ 1”的输入字段的值作为“ def”。 Need to know is there any other way to access element generated by *ngFor in angular.
需要知道还有其他方法可以访问* ngFor生成的angular元素。 Thanks
谢谢
Tag your inputs with a template variable: 使用模板变量标记您的输入:
<div *ngFor = "let ivalue of arraytoDispaly;let i = index;">
<input #inputs type="text" id={{i}} [value]="ivalue.inputValue" />
</div>
<button (click)='GetElementValue()'>GetElementValue</button>
Then you can use @ViewChildren
and query for the ElementRef using the QueryList
API: 然后,您可以使用
@ViewChildren
并使用QueryList
API查询QueryList
:
@ViewChildren('inputs',
{ read: ElementRef }) inputs: QueryList<ElementRef>;
The possible values for read
are: ElementRef
, ViewContainerRef
or name of the Component/Directive itself (useful if you have more than one directive on an element). 可能的
read
值是: ElementRef
, ViewContainerRef
或Component / Directive本身的名称(如果在一个元素上有多个指令,则很有用)。
Initialize the elements if you need to by implementing AfterViewInit
: 如果需要,可以通过实现
AfterViewInit
来初始化元素:
ngAfterViewInit(): void {
// so something with inputs
}
You also have access to inputs
via a click handler: 您还可以通过点击处理程序访问
inputs
:
GetElementValue(){
var t = (<HTMLInputElement> this.inputs.toArray()[1].nativeElement).value;
console.log(t);
}
Or more succinctly using map
: 或更简洁地使用
map
:
GetElementValue(){
var t = (<HTMLInputElement> this.inputs.map(t=>t.nativeElement)[1]).value;
console.log(t);
}
For more information, here is everything you need to know about how to use @ViewChildren: 有关更多信息,这是有关如何使用@ViewChildren的所有信息:
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
https://blog.angular-university.io/angular-viewchild/ https://blog.angular-university.io/angular-viewchild/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.