Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access to an ngModel element inside a reusable component

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}}">
like image 855
rematnarab Avatar asked Mar 07 '23 19:03

rematnarab


2 Answers

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);
}
like image 141
Suren Srapyan Avatar answered Mar 10 '23 09:03

Suren Srapyan


You also have to add {read: NgModel} with @ViewChild

@ViewChild('nameAccessor', {read: NgModel}) ngModel:NgModel;
like image 42
Anik Avatar answered Mar 10 '23 09:03

Anik