如何添加自定义角度材料垫错误

时间:2019-03-18 09:45:56

标签: angular angular-material

我有一个项目列表,现在我将输入框中的数据添加到该列表中。 我想在该输入框下显示重复输入的错误。

<mat-form-field>
    <input matInput (keyup)="validation()" [(ngModel)]="package">
    <mat-error>Duplicate Entry</mat-error>
</mat-form-field>   

建议我解决这种问题的正确方法。

2 个答案:

答案 0 :(得分:0)

我很少使用模板驱动的表单。我想你想要这样

<mat-form-field>
  <input matInput (keyup)="validation()" [(ngModel)]="package" name="package" #package="ngModel">
  <mat-error *ngIf="package.invalid">Duplicate Entry</mat-error>
</mat-form-field>

在mat-error中添加所需的错误消息

检查此链接https://angular.io/guide/forms#show-and-hide-validation-error-messages

答案 1 :(得分:0)

  1. 您需要使用 * ngIf隐藏或显示错误。如果发现重复项,则取一个变量并将其设为true。

示例:<mat-error *ngIf="duplicateFound">Duplicate Entry</mat-error>

  1. 当用户输入新项目时,您需要从当前项目列表中检查,如果已经存在,则将duplicateFound设置为true

您的模板

<input matInput (keyup.enter)="validation()" [(ngModel)]="package">

您的组件

duplicateFound: boolean = false;
items = [];

validation() {
  items.forEach(item => {
    if (item === this.package) {
      this.duplicateFound = true; // now your error will be displayed in browser
    }
  });
}