How to show reactive forms validation error messages

Issue

Hellow guys,

I’m struggling making a validator for a name input, I just replied the code from the angular wiki and still not working.

Could you please help me to find the problem?

Thanks in advise.

My HTML Code:

  <form [formGroup]="formAlta" (ngSubmit)="addRepresentacio()">
            <div class="form-group">
              <label for="namePro">Nom</label>
              <input id="namePro" class="form-control" formControlName="namePro" placeholder="Nom del professional" required>
              <div *ngIf="namePro.invalid && (namePro.dirty || namePro.touched)" class="alert alert-danger form-danger" role="alert">

        <div *ngIf="namePro.errors.required">
            El Nom del professional es obligatori
        </div>
    </div></form>

And my TS Component

 formAlta: FormGroup;
 ngOnInit() {
    this.formAlta = new FormGroup({
      idPro: new FormControl(),
      documentTypePro: new FormControl(),
      namePro: new FormControl('',[Validators.required]),
      rProfessional: new FormControl(this.tipusPro),
      firstSurnamePro: new FormControl(),
      secondSurnamePro: new FormControl(),
      businessNamePro: new FormControl(),
      idCli: new FormControl(),
      documentTypeCli: new FormControl(),
      nameCli: new FormControl('',Validators.required),
      rClient: new FormControl(this.tipusCli),
      firstSurnameCli: new FormControl(),
      secondSurnameCli: new FormControl(),
      businessNameCli: new FormControl(),
      idPermis: new FormArray([]),
      dateFiPermis: new FormArray([])
    });
  }

Solution

You should create a getter method in your component.ts as follows to get the form control in template

get formAltaControls(): any {
   return this.formAlta['controls'];
}

In your componen.html

<div *ngIf="formAltaControls.namePro.invalid && (formAltaControls.namePro.dirty || formAltaControls.namePro.touched)" class="alert alert-danger form-danger" role="alert">

    <div *ngIf="formAltaControls.namePro.errors.required">
        El Nom del professional es obligatori
    </div>

Answered By – Bear Nithi

Answer Checked By – David Goodson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.