Viewchild 在特定方法中未定义

Viewchild is undefined inside a specific method

我想禁用一个按钮,直到输入字段有 data.I 我正在尝试使用以下代码实现此目的。

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

但我收到以下错误“无法读取未定义的 属性 'nativeElement'”。 我可以在 addButtonClicked() 中访问 this.nameInput,但不能在 addButtonDisabled() 中访问。有人可以回答这个问题吗?

您应该将 static: true 设置为 ViewChild。默认为 false。

定义:

static - True 表示在更改检测运行之前解析查询结果,false 表示在更改检测之后解析。默认为假。

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

所以 nameInput 应该在 ngOnInit 上可用。

为了安全,你也应该使用safeCheck。

可选:最好更改方法名称以获得更好的约定,例如 isAddButtonDisabled。

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