0

页面加载输入应集中

<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(); 

}

单击 HighLight 按钮时,它会聚焦文本框,但是当我在 ngOnInit 上调用此方法时,它会给出错误无法读取未定义的属性“nativeElement”

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

1 回答 1

1

尝试实现AfterViewInit接口并专注于ngAfterViewInit()方法内部的输入(我猜,ngOnInit 有时会在视图尚未完全初始化时执行):

export class ParentComponent implements OnInit, AfterViewInit {

   @ViewChild('element') ref:ElementRef;

   focus(){
      this.ref.nativeElement.focus(); 
   }
  
   ngAfterViewInit() {
      this.focus();
   }
}
于 2021-08-29T17:34:16.020 回答