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 can create a
Custom Pipe
that checks first error equals with specified error:CUSTOM PIPE
You can have lots of error div but just one error will be shown:
Angular2 behind the scene checks the status of the control and reacts accordingly. So if you don't want to have more validation at a time, you can logically play with
AND(&&)
or/andOR(||)
or/andNOT(!)
operators.You could create a reusable component for showing errors so you don't need to repeat this code again and again.
You could create a custom pipe to get the first element of the errors object of the validator:
This way you would be able to display only one error:
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:
If you have consistent markup for your error message blocks, then you can use css to display only the first message and hide the rest:
css
markup