Access Template Reference Variables from Component Class

Access Template Reference Variables from Component Class
<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?
   }
}

2 Answers

That is a use-case for @ViewChild:

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

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

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

Here's a working demo:

9
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.