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}}">
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);
}
You also have to add {read: NgModel}
with @ViewChild
@ViewChild('nameAccessor', {read: NgModel}) ngModel:NgModel;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With