【发布时间】:2019-09-10 17:13:31
【问题描述】:
我有两个字段和一个按钮,一个简单的按钮。
如果我单击该按钮但未填写所有字段,则此按钮将被禁用,并且在每个字段中都会显示一条错误消息。
当触摸第一个字段时,如果我按下按钮,将显示错误消息,但仅针对第一个字段,并且要显示第二个字段的错误,我需要触摸该字段,但我需要如果我按下此按钮并且两个字段均未填写以显示错误消息。当我按下按钮并且字段不是两个字段仅在第一个字段时,我得到错误原因是触摸,但在第二个没有时,这就是我想要的。
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