如何一次只显示一个验证错误

问题描述:

我有此代码,可在我的表单上显示错误

I have this code to which displaying errors on my form

<input [ngFormControl]="form1.controls['thing']" type="text" id="thing" #thing="ngForm">
<div *ngIf='thing.dirty && !thing.valid'>
    <div class="err" *ngIf='thing.errors.required'>
        Thing is required.
    </div >
    <div class="err" *ngIf='thing.errors.invalid'>
        Thing is invalid.
    </div >
</div>

但是如果thing中有两个错误,则会显示两个错误. 可以说如果我的输入中包含5 validators,那么5 divs将会显示出来,这不是很好. 如何一次只显示一个error div?

But in case of thing has two errors in it the two error show up. Lets say if my input has 5 validators so 5 divs will show up which is not nice. How to display just one error div at a time?

您可以创建一个自定义管道来获取验证器的errors对象的第一个元素:

You could create a custom pipe to get the first element of the errors object of the validator:

@Pipe({
  name: 'first'
})
export class FirstKeyPipe {
  transform(obj) {
    var keys = Object.keys(obj);
    if (keys && keys.length>0) {
      return keys[0];
    }
    return null;
  }
}

这样,您将只能显示一个错误:

This way you would be able to display only one error:

@Component({
  selector: 'my-app',
  template: `
    <form>
      <input [ngFormControl]="form.controls.input1">
      <div *ngIf="form.controls.input1.errors">
        <div *ngIf="(form.controls.input1.errors | first)==='required'">
          Required
        </div>
        <div *ngIf="(form.controls.input1.errors | first)==='custom'">
          Custom
        </div>
      </div>
    </form>
  `,
  pipes: [ FirstKeyPipe ]
})
export class MyFormComponent {
  constructor(private fb:FormBuilder) {
    this.form = fb.group({
      input1: ['', Validators.compose([Validators.required, customValidator])]
    });
  }
}

请参阅此插件: https://plnkr.co/edit/c0CqOGuzvFHHh5K4XNnA?p=preview .

注意:与Günter同意创建可用组件;-)有关更多详细信息,请参见本文:

Note: agreed with Günter to create a usable component ;-) See this article for more details: