简体   繁体   中英

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);
}

Whenever I am clicking on 'GetElementValue' button, I am getting the value of input field with id of '1' as 'def'. Need to know is there any other way to access element generated by *ngFor in 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('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).

Initialize the elements if you need to by implementing AfterViewInit :

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

You also have access to inputs via a click handler:

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

Or more succinctly using 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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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