如何一次只显示一个验证错误
[英] How to display only single validation error at a time
本文介绍了如何一次只显示一个验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个代码在我的表单上显示错误
<div *ngIf='thing.dirty &&!thing.valid'><div class="err" *ngIf='thing.errors.required'>东西是必需的.</div ><div class="err" *ngIf='thing.errors.invalid'>东西无效.</div >
但是如果 thing
有两个错误,就会出现两个错误.假设我的输入有 5 个验证器
,那么 5 个 divs
会显示出来,这并不好.如何一次只显示一个 error div
?
解决方案
您可以创建一个自定义管道来获取验证器的错误对象的第一个元素:
@Pipe({名称:'第一个'})导出类 FirstKeyPipe {变换(对象){var 键 = Object.keys(obj);if (keys &&keys.length>0) {返回键[0];}返回空;}}
这样你就只能显示一个错误:
@Component({选择器:'我的应用',模板:`<表格><input [ngFormControl]="form.controls.input1"><div *ngIf="form.controls.input1.errors"><div *ngIf="(form.controls.input1.errors | first)==='required'">必需的
<div *ngIf="(form.controls.input1.errors | first)==='custom'">风俗
</表单>`,管道:[ FirstKeyPipe ]})导出类 MyFormComponent {构造函数(私人FB:FormBuilder){this.form = fb.group({input1: ['', Validators.compose([Validators.required, customValidator])]});}}
查看此 plunkr:https://plnkr.co/edit/c0CqOGuzvFHHh5K4XNnA?p=preview .
注意 :同意 Günter 创建一个可用的组件;-) 有关更多详细信息,请参阅此文章:
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>
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?
解决方案
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])]
});
}
}
See this plunkr: https://plnkr.co/edit/c0CqOGuzvFHHh5K4XNnA?p=preview .
Note : agreed with Günter to create a usable component ;-) See this article for more details:
这篇关于如何一次只显示一个验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!