【问题标题】:Angular problem to set an input to empty value将输入设置为空值的角度问题
【发布时间】:2020-07-03 04:26:45
【问题描述】:

我有一个带有搜索栏的表单,我想在单击“取消”或“保存”按钮后将栏的值设置为空:

这是我模板中的输入:

 <div class="input-group"><input type="text" class="form-control" name="searchTxt"  id="filtrer" [value]="searchEmpty" (input) = "onSearchTrigger(searchTxt.value)" placeholder="Rechercher un organisme financeur" #searchTxt>

两个按钮取消并保存在我的模板中:

  <div class="modal-footer"><button type="button" class="btn btn-default"
            data-dismiss="modal" (click) ="onModalCancel()">Annuler</button>
          <button type="submit" class="btn btn-primary" (click)="onSubmit()" data-dismiss="modal"
            [disabled]="!registrationForm.valid"> Valider</button></div>
      </div>

在我的组件中,我有两个功能:

  onSubmit() {
this.isSubmitted = true;
if (!this.registrationForm.valid) {
  return false;
  // tslint:disable-next-line: no-else-after-return
} else {
  this.myCodeOrganisme = this.registrationForm.value.orga;
  this.serviceHttp2.getAllOrganismes().subscribe(resp => (this.organismesFinanceurs = resp));
  for (const organisme of this.organismesFinanceurs) {
    if (organisme.code === this.myCodeOrganisme) {
      this.myLibelleOrganisme = organisme.libelleLong;
    }
  }
  this.isSubmitted = false;
  this.searchEmpty = '';
}
  }

  onModalCancel() {
this.searchEmpty = null;
  }

控制台返回这个错误:

ExpressionChangedAfterItHasBeenCheckedError:检查后表达式已更改。

那么如何将输入搜索栏设置为空??

谢谢

【问题讨论】:

  • 您是否在单击按钮或初始页面加载时收到此错误
  • 点击按钮时出现此错误
  • 你为什么在onSubmit方法中返回false?您可以放心地省略 false 关键字,因为您可能没有在任何地方使用返回值。

标签: angular input


【解决方案1】:

您设置的组件属性不在服务器响应的订阅中。您正在循环通过this.organismesFinanceurs 并设置新属性,然后服务器响应正在更新this.organismesFinanceurs。尝试在 Http 请求的订阅中移动此功能(见下文):

onSubmit() {
  this.isSubmitted = true;
  if (!this.registrationForm.valid) {
    return false;
    // tslint:disable-next-line: no-else-after-return
  } else {
    this.myCodeOrganisme = this.registrationForm.value.orga;
    this.serviceHttp2.getAllOrganismes().subscribe(resp => {
      this.organismesFinanceurs = resp;

      for (const organisme of this.organismesFinanceurs) {
        if (organisme.code === this.myCodeOrganisme) {
          this.myLibelleOrganisme = organisme.libelleLong;
        }
      }
      this.isSubmitted = false;
      this.searchEmpty = '';
    });
  }
}

【讨论】:

    猜你喜欢
    • 2017-10-28
    • 1970-01-01
    • 2020-03-27
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    相关资源
    最近更新 更多