【问题标题】:Viewchild is undefined inside a specific methodViewchild 在特定方法中未定义
【发布时间】:2022-01-13 23:42:44
【问题描述】:

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

<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() 中访问。有人可以回答这个问题吗?

【问题讨论】:

  • 你可能不应该这样做[disabled]="addButtonDisabled()"。这将多次调用该函数(并且可能在初始化nameInput 之前?)我会做一些事情,例如向组件添加isDisabled 属性,执行[disabled]="isDisabled",然后让addButtonClicked 更新该属性。跨度>

标签: html angular typescript ionic-framework


【解决方案1】:

你应该把 static: true 放到 ViewChild。默认为假。

定义:

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

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

所以 nameInput 应该在 ngOnInit 上可用。

为了安全,您还应该使用 safeCheck。

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

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

【讨论】:

    猜你喜欢
    • 2021-07-26
    • 2019-03-15
    • 2017-03-11
    • 2023-03-21
    • 2019-10-03
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    相关资源
    最近更新 更多