Access template reference variables from component class

jackOfAll picture jackOfAll · Sep 22, 2016 · Viewed 89.7k times · Source
<div>
   <input #ipt type="text"/>
</div>

Is it possible to access the template access variable from the component class?

i.e., can I access it here,

class XComponent{
   somefunction(){
       //Can I access #ipt here?
   }
}

Answer

mxii picture mxii · Sep 22, 2016

That is a use-case for @ViewChild:

https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html

class XComponent {
   @ViewChild('ipt', { static: true }) input: ElementRef;

   ngAfterViewInit() {
      // this.input is NOW valid !!
   }

   somefunction() {
       this.input.nativeElement......
   }
}

Here's a working demo:

https://stackblitz.com/edit/angular-viewchilddemo?file=src%2Fapp%2Fapp.component.ts