import { Component , OnInit } from '@angular/core' ; import { FormArray , FormBuilder , FormGroup , Validators } from '@angular/forms' ; @ Component ( { selector : 'app-root' , templateUrl : './app.component.html' , styleUrls : [ './app.component.scss' ] } ) export class AppComponent implements OnInit { public form : FormGroup ; public contactList : FormArray ; get contactFormGroup ( ) { return this . form . get ( 'contacts' ) as FormArray ; } constructor ( private fb ) { } ngOnInit ( ) { this . form = this . fb . group ( { name : [ null , Validators . compose ( [ Validators . required ] ) ] , organization : [ null ] , contacts : this . fb . array ( [ this . createContact ( ) ] ) } ) ; this . contactList = this . form . get ( 'contacts' ) as FormArray ; } createContact ( ) { return this . fb . group ( { type : [ 'email' , Validators . compose ( [ Validators . required ] ) ] , name : [ null , Validators . compose ( [ Validators . required ] ) ] , value : [ null , Validators . compose ( [ Validators . required , Validators . email ] ) ] } ) ; } addContact ( ) { this . contactList . push ( this . createContact ( ) ) ; } removeContact ( index ) { this . contactList . removeAt ( index ) ; } changedFieldType ( index ) { let validators = null ; if ( this . getContactsFormGroup ( index ) . controls [ 'type' ] . value === 'email' ) { validators = Validators . compose ( [ Validators . required , Validators . email ] ) ; } else { validators = Validators . compose ( [ Validators . required , Validators . pattern ( new RegExp ( '^\\+[0-9]?()[0-9](\\d[0-9]{9})$' ) ) ] ) ; } this . getContactsFormGroup ( index ) . controls [ 'value' ] . setValidators ( validators ) ; this . getContactsFormGroup ( index ) . controls [ 'value' ] . updateValueAndValidity ( ) ; } getContactsFormGroup ( index ) { const formGroup = this . contactList . controls [ index ] as FormGroup ; return formGroup ; } submit ( ) { console . log ( this . form . value ) ; } }