I'm having a array form namely "address" and this will be a dynamic once the user clicks the "Add Address" button immediately one address form will add. I implemented this with an issue (Add/Remove address works fine). Now I need to add a dynamic contact numbers similar like address.
A address may contain one or more than one phone numbers, if the user clicks "Add Phone number" need to add a new phone number form inside the address form, the functionality will required in all the address forms. (i.e., array of array => array of address and each address contains array of contacts)
Working code is available in StackBlitz: https://stackblitz.com/edit/angular-maexn8
Sample Code:
import { Injectable } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
import { User } from '../../model/user';
@Injectable()
export class UpsertUserFormService {
public userForm: FormGroup;
constructor(private _fb: FormBuilder) {
this.userForm = this._fb.group({
relation: [],
title: [],
firstName: [],
lastName: [],
address: this._fb.array([this.addAddressGroup()])
});
}
private addAddressGroup(): FormGroup {
return this._fb.group({
street: [],
city: [],
state: [],
pincode: [],
isPrimary: [],
contacts: this._fb.array([this.contactsGroup()])
});
}
showMessage(obj: any) {
console.log('Console Item: ',obj)
}
private contactsGroup(): FormGroup {
return this._fb.group({
phoneNumber: ['9712345678', [Validators.maxLength(10)]],
});
}
addAddress(): void {
this.addressArray.push(this.addAddressGroup());
console.log(this.addressArray);
}
removeAddress(index: number): void {
this.addressArray.removeAt(index);
}
get addressArray(): FormArray {
return <FormArray>this.userForm.get('address');
}
}
Kindly assist me how to implement dynamic nested array forms (Add/Remove forms).
You need to declare according to the
formGroup
orformArrays
properly.You can use this as reference.
Edit
Forked your code: here. As mentioned above, keep the
group/array/controls
in orderApp.component.ts
Try the following way. Pass the index for the address in view and read the contacts element for that particular address and add a new contactGroup.
Hope this helps!!!