如何访问可重用组件中的 ngModel 元素



我的可重用组件中有一个ngModel组件。该字段不是表单的一部分。我想访问它以进行一些更改。我已经尝试了以下代码,但它在 OnInit 中未定义。你能告诉我如何访问它吗?

下面的代码返回未定义

@ViewChild('nameAccessor') ngModel:NgModel;
ngOnInit(): void {
    console.log(this.ngModel);
}

模板

<input ngModel (blur)="nameBoxChanged(nameAccessor)" (keyup)="nameBoxChanged(nameAccessor)" [ngClass]="{'redBorder':nameBoxValidator}"
      #nameAccessor [disabled]="pageStatus==4" name="name" id="name" type="text" class="form-control" placeholder="{{'movieCategory.placeHolder.name'|translate}}">

还必须使用@ViewChild添加{read: NgModel}

@ViewChild('nameAccessor', {read: NgModel}) ngModel:NgModel;

尝试通过ViewChild获取的元素在OnInit生命周期事件中尚未准备就绪。您可以在生命周期事件AfterViewInit获取元素。

文档

视图查询是在调用 ngAfterViewInit 回调之前设置的。

代码块。在ngAfterViewInit回调中访问您的字段。

@ViewChild('nameAccessor') ngModel:NgModel;
ngOnInit(): void {
}
ngAfterViewInit(): void {
   console.log(this.ngModel);
}

在ngOnInit中,尚未设置@ViewChild。你应该使用 ngAfterViewInit。

最新更新