Aman Gupta Aman Gupta - 4 months ago 36
TypeScript Question

angular 2 / typescript : get hold of an element in the template

Does anybody know how to get hold of an element defined in a component template? Polymer makes it really easy with the $ and $$.
I was just wondering how to go about it in Angular 2.

Take the example from the tutorial:

/**
* Created by amgu on 9/14/2015.
*/
import {Component} from '@angular/core'

@Component({
selector:'display'
template:`

<input #myname (input) = "updateName(myname.value)"/>
<p> My name : {{myName}}</p>

`

})
export class DisplayComponent{
myName: string;
updateName: Function;
constructor(){

this.myName = "Aman";
this.updateName = function(input: String){

this.myName = input;

};

}

}


How do I catch hold of a reference of the 'P' or 'input' element from within the class definition?

Answer

You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor:

constructor(myElement: ElementRef) { ... }

Docs: https://angular.io/docs/ts/latest/api/core/index/ElementRef-class.html