angularviewchild

@ViewChild is undefined in afterViewInit using FormControl


I have an nbInput with FormControl: https://akveo.github.io/nebular/docs/components/input/overview#nbinputdirective

I want to access this in controller using @ViewChild but it returns undefined. Following is my code:

<section>
 <nb-form-field>
    <nb-icon nbPrefix [icon]="vm.icon"></nb-icon>
    <input
      #inputField
      class="input"
      type="text"
      nbInput
      [formControl]="input"
      placeholder="{{ vm.placeholder }}"
      (blur)="onBlur()"
      [nbDatepicker]="datePicker"
    />
    <nb-rangepicker #datePicker></nb-rangepicker>
  </nb-form-field>
</section>

@ViewChild('inputField') inputField: ElementRef;
  ngAfterViewInit(): void {
    console.log(this.inputField); //returns undefined
  }

Solution

  • Since you use rxLet the viewchild won't be available at afterViewInit.

    You have 2 possibilites :