// below angularReactiveform is the user defined form name , the form name may be any as per your choice
//Dynamically add new field to a reactive form
this.angularReactiveform.addControl(‘filedName’);

// Dynamically adding filed array
this.angularReactiveform.addControl(‘filedName’, this.formBuilder.array([]));

//add validators dynamically to a form control dynamically
this.angularReactiveform.get(‘filedName’).setValidators([Validators.required]);

this.angularReactiveform.controls[‘filedName’].updateValueAndValidity()

//remove validators from a form control dynamically
this.angularReactiveform.get(‘filedName’).clearValidators();

this.angularReactiveform.controls[‘filedName’].updateValueAndValidity()

// Dynamically remove control to a reactive form filed
this.packageForm.removeControl(‘filedName’);

// form control array type
fieldArrayFormat(datarow) {
return this.formBuilder.group({
id:[datarow.id],
price: [datarow.price],
})
}
foreach(datarows as datarow){
(this.angularReactiveform.controls[‘fieldName’] as FormArray).push(this.fieldArrayFormat(datarow));
}

// we can write the above line as

get filedArray() {
return this.angularReactiveform.get(‘fieldName’) as FormArray;
}

foreach(datarows as datarow){
this.filedArray.push(this.fieldArrayFormat(datarow));
}

or directly

foreach(datarows as datarow){
this.filedArray.push(this.formBuilder.group({id:datarow.id,price:datarow.price}));
}
//Dynamically removing control by index number in reactive form having array type form filed

(this.angularReactiveform.controls[‘fieldName’] as FormArray).removeAt(3)

How to use form Array in HTML File


Leave comment

Your email address will not be published. Required fields are marked with *.