Viewchild is undefined inside a specific method

I want to disable a button until the input field has data.I am trying to achieve this with the below code.

<ion-row>
    <ion-input clear-input
      id="globalmsg-user-management-name"
      #nameInput>
    </ion-input>
</ion-row>

<ion-row>
    <ion-button
        #globalmsgAddButto
        id="globalmsg-user-management-add-button"
        (click)="addButtonClicked()"
        [disabled]="addButtonDisabled()"
        >
      <span>Add</span>
    </ion-button>
 </ion-row>
@ViewChild('nameInput') nameInput: ElementRef;
  addButtonDisabled()
  {    
    if ( this.nameInput.nativeElement.value === '') {
      return true;
    }
    else {
      return false;
    }
  }

But I get the following error "Cannot read property 'nativeElement' of undefined". I could access this.nameInput in addButtonClicked() but not in addButtonDisabled().Can someone answer this Please?


You should put static: true to ViewChild. By default it is false.

Defintion:

static - True to resolve query results before change detection runs, false to resolve after change detection. Defaults to false.

@ViewChild('nameInput', {static: true}) nameInput: ElementRef;

So nameInput should be available on ngOnInit.

For safety, you should also use safeCheck.

Optionally: better to change method name for better convention like isAddButtonDisabled.

  public isAddButtonDisabled(): boolean {    
    if (this.nameInput?.nativeElement?.value === '') {
      return true;
    } else {
      return false;
    }
  }