155
<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 2

210

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

update demo using angular v18:

https://stackblitz.com/edit/angular-v18-viewchild?file=src%2Fmain.ts

which also considers the new signal way of using ViewChildren: https://angular.dev/api/core/viewChild?tab=usage-notes

Sign up to request clarification or add additional context in comments.

11 Comments

But on debugging I am getting this.input itself as undefined.
As i mentioned, its only available AFTER the event ngAfterViewInit() was fired. You have to import ViewChild from '@angular/core` ..
But how can we set a value? I've tried this.ipt.nativeElement.setAttribute('value', 'xxx'); but nothing happens. And there are no methods like value() or setValue(), even if I declare it of type HTMLInputElement (I'm basing this on IDE's code hinting/autocomplete). In my case, I don't care about reading the value. I just need to set different values.
Currently in Holiday.. did you tried setProperty also?
shouldnt this.input.nativeElement.value = 'test' work?! maybe there are special behaviors with forms and their bindings.
|
5
@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.

1 Comment

or @ViewChild('modal reference variable', { static: true }) name: ElementRef | undefined; so you dont forget it really is undefined before ngAfterViewInit()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.