如何访问可重用组件内的 ngModel 元素 [英] How to access to an ngModel element inside a reusable component

查看:26
本文介绍了如何访问可重用组件内的 ngModel 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的可重用组件中有一个 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 ?

下面的代码返回 undefined

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆