角度:-不显示并隐藏错误消息

时间:2018-08-02 18:10:15

标签: angular angular5 angular6

下面是对提交按钮的onclick正常工作的代码,如果它的错误,那么它将仅在提交按钮上显示错误,并且一旦用户填写正确的信息,它就会不断出现,并且仅在单击提交按钮时才出现,即条件正在为提交按钮工作,但不适用于表单本身。我想我正在跳过某事

下面是HTML文件

<div class="col-sm-6 pb-3 zip-wrapper">
              <label for="mailingZip" class="required">Zip Code</label>
              <div class="input-wrapper">
                <input type="text" name="mailingZip" [maxLength]="20" [disabled]="setAsResidential" placeholder="Enter Zip Code" [(ngModel)]="mailingAddress.zip.value"
                  autocomplete="off" (keyup)="validateMailingZipCode()" (blur)="validateMailingZipCode()">
              </div>

              <div class="clearfix"></div>
              <p *ngIf="mailingAddress.zip.error" class="clearfix error-message">
                <i class="fa fa-exclamation-triangle" aria-hidden="true"></i> {{mailingAddress.zip.errorMessage}}</p>
            </div>

下面是ts文件

 validateMailingZipCode() {
    let hasErrors: boolean = false;
    if (parseInt(this.mailingAddress.zip.value) >= parseInt('01001') && this.mailingAddress.zip.value.length === 5) {
      return false;
    } else {
      hasErrors = true;
      this.mailingAddress.zip.error = true;
      this.mailingAddress.zip.errorMessage = 'Invalid Zip Code Provided';
    }
    return hasErrors;
  }

1 个答案:

答案 0 :(得分:2)

只需重置功能中的this.mailingAddress.zip.error

validateMailingZipCode() {
  this.mailingAddress.zip.error = false; // Reset to false on keyup
  let hasErrors: boolean = false;
  if (parseInt(this.mailingAddress.zip.value) >= parseInt('01001') && this.mailingAddress.zip.value.length === 5) {
    return false;
  } else {
    hasErrors = true;
    this.mailingAddress.zip.error = true;
    this.mailingAddress.zip.errorMessage = 'Invalid Zip Code Provided';
  }
  return hasErrors;
}