Login Or Sign up

Focus on MatInput on page load giving error

52 Views Asked by At

On page load input should be focused

<mat-form-field>
          <input matInput #element placeholder="username" >
                 
    <button type="button" (click)="focus()" class="btn btnStyles" >HighLight</button>
@ViewChild('element') ref:ElementRef;


focus(){
this.ref.nativeElement.focus(); 

}

On click of HighLight button its focusing the text box but when i call this method on ngOnInit its giving error Cannot read property 'nativeElement' of undefined

ngOnInit() {
this.focus();
}
1

There are 1 best solutions below

1
Dorin Baba On

Try to implement the AfterViewInit interface and to focus on your input inside ngAfterViewInit() method (ngOnInit sometimes executes when the view has not been fully initialized, I guess):

export class ParentComponent implements OnInit, AfterViewInit {

   @ViewChild('element') ref:ElementRef;

   focus(){
      this.ref.nativeElement.focus(); 
   }
  
   ngAfterViewInit() {
      this.focus();
   }
}