0

I'm working on a form using Angular 4 (reactive forms), my problem is I cant show individually the error messages for the email address field.

I'm trying this format but no luck.

<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 *ngIf="name.errors.forbiddenName">
    Name cannot be Bob.
  </div>

This is my sample code

register.component.ts

constructor(private fb: FormBuilder) { 

    this.rForm = fb.group({

    'account': [null, Validators.required],
    'company': [null, Validators.required],
    'website': '',
    'email': [null, Validators.compose([Validators.email, Validators.required])],
    'phone': [null, Validators.required],

    })

  }

register.component.html

<div class="col-md-6">
    <label>Email Address</label>
    <input type="email" name="email" class="form-control" formControlName = "email">
    <span class="text-danger" *ngIf="!rForm.controls['email'].valid && rForm.controls['email'].touched">This field is required. Please provide a valid email address.</span>

Thanks.

1 Answer 1

3

First, you should use rForm.get('email').valid instead of rForm.controls['email'].valid.

An easier way to do it is to add the following code to your class:

get email() { return this.rForm.get('email'); }

That way instead of using rForm.get('email').valid in your template, you can use email.valid.

I have put together a working plnkr here (http://plnkr.co/edit/bDANlDxej3hAKQFx9sra?p=preview)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.