如何访问可重用组件内的ngModel元素 [英] How to access to an ngModel element inside a reusable component
问题描述
我的可重用组件中有一个ngModel组件.该字段不是表单的一部分.我想访问它进行一些更改.我已经尝试了以下代码,但在OnInit中未定义.您能告诉我如何使用它吗?
I have an ngModel component inside my reusable component. The field is not part of a form. I would like to access to it to do some changes. I have tried the below code but it comes undefined in OnInit. Could you tell me how to access it ?
下面的代码返回未定义的
Below code returns undefined
@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
获取的元素在OnInit
生命周期事件中尚未准备就绪.您可以在AfterViewInit
生命周期事件中获取该元素.
Elements which are tried to be got via ViewChild
are not ready at the OnInit
life cycle event. You can get the element in AfterViewInit
life cycle event.
从> 文档
视图查询是在调用ngAfterViewInit回调之前设置的.
View queries are set before the ngAfterViewInit callback is called.
代码块.在ngAfterViewInit
回调中访问您的字段.
Code block. Access your field in the ngAfterViewInit
callback.
@ViewChild('nameAccessor') ngModel:NgModel;
ngOnInit(): void {
}
ngAfterViewInit(): void {
console.log(this.ngModel);
}
这篇关于如何访问可重用组件内的ngModel元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!