我有这个代码在我的表单上显示错误
<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>
但是如果事情中有两个错误,则会出现两个错误.
让我们说如果我的输入有5个验证器,那么将显示5个div,这是不好的.
如何一次只显示一个错误div?
您可以创建自定义管道以获取验证器的errors对象的第一个元素:
@Pipe({ name: 'first' }) export class FirstKeyPipe { transform(obj) { var keys = Object.keys(obj); if (keys && keys.length>0) { return keys[0]; } return null; } }
@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])] }); } }
看到这个plunkr:https://plnkr.co/edit/c0CqOGuzvFHHh5K4XNnA?p=preview.
注意:与Günter同意创建可用组件;-)有关详细信息,请参阅此文章:
> http://restlet.com/blog/2016/02/17/implementing-angular2-forms-beyond-basics-part-2/