How to access to an ngModel element inside a reusable component

你。 提交于 2019-12-22 12:36:22

问题


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

Template

<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}}">

回答1:


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.

From the Documentation

View queries are set before the ngAfterViewInit callback is called.

Code block. Access your field in the ngAfterViewInit callback.

@ViewChild('nameAccessor') ngModel:NgModel;

ngOnInit(): void {

}

ngAfterViewInit(): void {
   console.log(this.ngModel);
}



回答2:


In ngOnInit, the @ViewChild are not yet setted. You should use ngAfterViewInit.



来源:https://stackoverflow.com/questions/46805611/how-to-access-to-an-ngmodel-element-inside-a-reusable-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!