I created a dynamic form array where clicking the add contact button inserts a dynamic form field. I successfully implemented validation for the form fields (using validator.required, validator.pattern, etc.).
However, when attempting to display an error message in the HTML view:
<md-error *ngIf="myForm.controls.myContactArray.controls['name'].hasError('required')">
Email is <strong>required</strong>
</md-error>
The following error message occurred:
core.es5.js:1020 ERROR TypeError: Cannot read property 'hasError' of undefined
at Object.eval [as updateDirectives] (RegisterComponent.ngfactory.js:453)
at Object.updateDirectives (core.es5.js:12770)
...
HTML
<div class="container-fluid">
<md-card>
<button (click)="addColumn()" md-raised-button>Add Contacts</button>
<hr>
<form [formGroup] = "myForm" (ngSubmit) = "save(myForm.value)" class="contact-form">
<div formArrayName="myContactArray">
<div *ngFor="let myGroup of myForm.controls.myContactArray.controls; let rowIndex = index" >
...
<button md-raised-button type="submit" *ngIf="myForm.controls.myContactArray.controls.length > 0" [disabled] = "!myForm.valid">Submit</button>
</form>
</md-card>
</div>
TypeScript
import {Component,OnInit} from '@angular/core';
import {FormControl,FormBuilder,FormGroup,FormArray,Validators} from '@angular/forms';
const EMAIL_REGEX = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
...
@Component({
moduleId: module.id,
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
...
}