Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 How to get reference of HTML elements generated dynamically

I have this inputs generated dynamically:

  <div *ngFor="let cell of column; let i = index;">           <!-- Material design input-->           <md-input id="my-input-{{i}}">           </md-input>   </div> 

Please notice id=my-input-{{i}} I would like to get a reference to the DOM element based on this dynamic id. This input can be 3, 6 or more inputs so I need to access the id dynamically and get a hold to it.

like image 427
CommonSenseCode Avatar asked Nov 10 '16 18:11

CommonSenseCode


2 Answers

The only response is

let elem:Element = document.getElementById("myProgrammaticallyChosenIndex")

No other angular weird ceremony needed

Tested on angular 4+

like image 113
David Faure Avatar answered Oct 02 '22 20:10

David Faure


Use ElementRef class from @angular/core to get the parent element and then create an HTMLElement to get its dynamic elements by class name.

Component:

declare var $: any; //intentional use of jQuery-not recommended though  @Component({   selector: 'my-app',   template: `     <input type='button' (click)='addDiv()' value='Add New Div' />      <input type='button' (click)='selectDiv()' value='Select' />   ` }) export class App {   constructor(private elRef: ElementRef) {   }    addDiv() {     /*intentional use of jQuery for appending new div      give a class to your dynamic elements*/      $('my-app').append("<div class='foo'>Hello I'm Dynamic!</div>");   }    selectDiv() {     //create a new HTMLElement from nativeElement     var hElement: HTMLElement = this.elRef.nativeElement;      //now you can simply get your elements with their class name     var allDivs = hElement.getElementsByClassName('foo');      //do something with selected elements     console.log(allDivs);   } } 

Working Plunker

Edit: I used jQuery only for quick demo purpose here. Otherwise, you should not use jQuery with Angular.

like image 31
Syed Ali Taqi Avatar answered Oct 02 '22 18:10

Syed Ali Taqi