8

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 :)

1
  • Have you tried the posted link answer? Commented Jul 7, 2019 at 7:15

1 Answer 1

-1

Hopefully this will help you.

Simple Solution but not a generic one.

It needs to be changed for displaying Validation errors.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.