One challenge I'm facing involves a form array structured as follows:
this.myForm = this.fb.group({
arr: this.fb.array([this.createItem()])
})
I have the ability to dynamically append fields to the array using the following methods:
createItem() {
return this.fb.group({
name: [''],
pay: [''],
type: []
})
addItem() {
this.arr = this.myForm.get('arr') as FormArray;
this.arr.push(this.createItem());}
The 'type' control operates as a dropdown with the following values:
types = [
{ id: 10, name: 'A' },
{ id: 20, name: 'B' },
{ id: 30, name: 'C' },
];
My main concern arises when a user selects Type 'A' for a group. In such cases, I aim to include two additional fields: 'phone' and 'address'. Conversely, for selections of 'B' and 'C', I do not want these extra fields added.
For instance, if a user opts for 'A' in the first entry of the form Array, I will introduce controls for 'phone' and 'address' within the 'this.fb.group'. If the user switches to 'B' or 'C' for that specific row in the array, I will remove these two fields accordingly.
To achieve this functionality, I am keen on subscribing to the changes in the 'type' form control, enabling me to add or delete controls based on the selected type. However, I am uncertain about the exact implementation steps. Reference stackblitz can be found here.