I'm starting to create my first Angular 4 app. I'm testing form validation. I created a template-driven form and I added some validators.
Now, I want to display validation errors for a field. This is my actual code :
<input id="name" name="name" class="form-control" required minlength="4" [(ngModel)]="name" #name="ngModel">
<div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
<div *ngIf="name.errors.required">
Name is required.
</div>
<div *ngIf="name.errors.minlength">
Name must be at least 4 characters long.
</div>
</div>
I'm afraid to write this for every input in my form! Is it possible to write something like that (of course, I tried this code but it didn't work):
<div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger">
<p *ngFor="let error on name.errors">{{error}}</p>
</div>
Thanx for your help :)
Hopefully this will help you.
Simple Solution but not a generic one.
It needs to be changed for displaying Validation errors.