How can I add a formcontrol(option)
dynamically in formarray
? I want to dynamically add questions to a formarray
. Upon clicking a butt
This example dynamically adds email fields to a reactive form. This would be used to enable users to add multiple email addresses (e.g. Home and Work).
This demo has the following dependencies: Angular 8, Angular Material, Bootstrap 4
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.emailForm = this.formBuilder.group({
emails: this.formBuilder.array([this.createEmailFormGroup()])
});
}
FormGroup
private createEmailFormGroup(): FormGroup {
return new FormGroup({
'emailAddress': new FormControl('', Validators.email),
'emailLabel': new FormControl('')
})
}
FormGroup
to the FormArray
public addEmailFormGroup() {
const emails = this.emailForm.get('emails') as FormArray
emails.push(this.createEmailFormGroup())
}
FormGroup
public removeOrClearEmail(i: number) {
const emails = this.emailForm.get('emails') as FormArray
if (emails.length > 1) {
emails.removeAt(i)
} else {
emails.reset()
}
}