Search code examples
angulartypescriptangular-ngmodel

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

Solution

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