【问题标题】:How to display a error for a form field when other field is touch? [duplicate]触摸其他字段时如何显示表单字段的错误? [复制]
【发布时间】:2019-09-10 17:13:31
【问题描述】:

我有两个字段和一个按钮,一个简单的按钮。

  1. 如果我单击该按钮但未填写所有字段,则此按钮将被禁用,并且在每个字段中都会显示一条错误消息。

  2. 当触摸第一个字段时,如果我按下按钮,将显示错误消息,但仅针对第一个字段,并且要显示第二个字段的错误,我需要触摸该字段,但我需要如果我按下此按钮并且两个字段均未填写以显示错误消息。当我按下按钮并且字段不是两个字段仅在第一个字段时,我得到错误原因是触摸,但在第二个没有时,这就是我想要的。

HTML

<div *ngIf="data.softwareCategoriesRenderComponent === true ||  data.industry === true">
      <h4>Please write the {{data.itemName}} name in EN *.</h4>
      <mat-form-field>
        <input matInput [formControl]="name" required [(ngModel)]="data.newItemName" maxlength="20"
          (focus)="focusFunction()" (focusout)="focusOutFunction()">
        <mat-error *ngIf="name.invalid">The  English name is required </mat-error>
      </mat-form-field>
      <div class="dialog-margin">
        <span class="mat-body-1">Maximum of 50 characters</span>
      </div>
      <h4>Please write the {{data.itemName}} name in CZ *.</h4>
      <mat-form-field >
        <input matInput [formControl]="nameCZ" required [(ngModel)]="data.newCZItemName" maxlength="20"
          (focus)="focusFunction()" (focusout)="focusOutFunction()">
        <mat-error *ngIf="!show">The  Czech name is required </mat-error>
        <mat-error *ngIf="nameCZ.invalid">The  Czech name is required </mat-error>
      </mat-form-field>
      <div class="dialog-margin">
        <span class="mat-body-1">Maximum of 50 characters</span>
      </div>
    </div>

TS:

name = new FormControl('', [Validators.required]);
  nameCZ = new FormControl('', [Validators.required]);
  focusOutFunction() {
    if (this.data.softwareCategoriesRenderComponent === true) {
      if (this.name.valid && this.nameCZ.valid) {
        this.show = true;
      } else {
        this.show = false;
      }
    }
  }

  focusFunction () {
    this.show = true;
  }

【问题讨论】:

  • 试试这个stackblitz demo
  • 正在使用div,你可能会看到我想使用mat-error 我没有机会选择,但是谢谢
  • 我作为骗子提供的链接应该极大地帮助您使用两种方法在两个控件上使用验证。然后,您将不得不调整您的代码(因为您的验证不同)。如果您在实现自己的代码时遇到任何问题,请随时在minimal reproducible example 中提出有关上述问题的新问题!

标签: angular typescript


【解决方案1】:

看这个demo你可以通过https://stackblitz.com/edit/angular-simple-template-driven-form轻松理解

【讨论】:

  • 一开始我说的是一个简单的按钮,意思不是提交按钮,我知道如何通过提交或者我有一个表单组来获得它,但我这里的代码就是我所拥有的
  • 在我的代码中,如果您触摸并进一步移动,则无需单击提交按钮即可收到错误
  • 您可以将该提交按钮转换为简单的,然后结果是相同的,没有任何变化。试一次
  • 如果我触摸我会得到错误但如果我触摸第一个并且我点击按钮我需要一种关于它的条件
  • 你不能点击按钮,因为如果任何字段为空,那么按钮将无法点击,只需检查一下
猜你喜欢
  • 2019-06-30
  • 2022-07-26
  • 1970-01-01
  • 2022-01-19
  • 1970-01-01
  • 2015-05-24
  • 1970-01-01
  • 2016-05-27
  • 1970-01-01
相关资源
最近更新 更多