Access template reference variables from component class

AngularTypescriptAngular2 Template

Angular Problem Overview


<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?
   }
}

Angular Solutions


Solution 1 - Angular

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

Solution 2 - Angular

@ViewChild('modal reference variable', { static: true }) name: ElementRef;

sometimes it doesn't work on modal. so when I used modal in angular it gives an error so I use this.

@ViewChild('modal reference variable', { static: true }) name!: ElementRef;

it will definitely work if you want the modal to be executed without clicking the button.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRohit RaneView Question on Stackoverflow
Solution 1 - AngularslaeshView Answer on Stackoverflow
Solution 2 - AngularAyush RawatView Answer on Stackoverflow