Search code examples
angularelementref

ElementRef is undefined even after calling in ngAfterViewInit()


I have created an ElementRef variable but when I am logging it, it's showing undefined. I've tried calling it inside ngAfterViewInit but that too doesn't work. I am calling a form on a popup window and writing the whole code to open the popup on the same component. In that form, I've defined ElementRef variable to one of the fields but when I am logging the same, it is showing undefined. Please help me out in this by letting me know what wrong I've been doing.

HTML code:

  <input #testDesc matInput autocomplete="off" placeholder="Description" formControlName="description" name="description" required>

TS code:

@ViewChild("testDesc") testDescRef: ElementRef<HTMLInputElement>;

 ngAfterViewInit() {
    console.log(this.testDescRef); // calling here.
  }

openAddEditDialog(){ // this is being called to open the form.
    console.log(this.testDescRef); //calling here as well and it is also undefined.

}

Solution

  • If your form is in a popup, you need "wait" Angular show the popup. Some like

    showForm(){
       this.popUp.show(); //or whatever you makes to show the popup
       setTimeout(()=>{
         console.log(this.testDescRef)
       })
    }
    

    The setTimeout without miliseconds say to Angular: "Hey, when you finish to repaint, don't forget execute the instructions under the setTimeout".

    The same happens when you have the element with a template reference variable under a *ngIf, first you makes the condition true and, enclosed in a setTimeout execute the actions. This is not necessary if you use display none, but yes if you have not the "element" in the DOM when you try to "reach" it.