here is the code I need to create a form-control dynamically hear this. products like an array, I need to create a form control based on the array (products), i am expected same like out put can anyone help me out this issue
ngOnInit() {
this.form = this.fb.group({
SelectAll: new FormControl(''),
genericTextBox: new FormControl(''),
dateRangeTO: new FormControl('', [Validators.required]),
dateRangeFrom: new FormControl('', [Validators.required]),
products: this.fb.array(
this.products.map((x) =>
this.fb.group((x) =>
this.form.addControl(x.name, new FormControl(''))
)
)
),
});
products = [
{
id: 1,
name: 'AAA',
displayName: 'aaaaaa',
selected: false,
},
{
id: 2,
name: 'BBB',
displayName: 'bbbbbb',
selected: false,
},
];
expected output for form control structure, console.log(this.form.value);
{
"genericTextBox": "",
"dateRangeTO": "",
"dateRangeFrom": "",
"SelectAll": "",
"products": {
"AAA": "",
"BBB": "",
}
}
CodePudding user response:
I don't think there is a need to do this.fb.array
since what you want as per the output is a FormGroup
and not an array. You can do the following:
ngOnInit() {
this.form = this.fb.group({
SelectAll: new FormControl(''),
genericTextBox: new FormControl(''),
dateRangeTO: new FormControl('', [Validators.required]),
dateRangeFrom: new FormControl('', [Validators.required]),
products: new FormGroup({})
})
this.populateProductForm();
// get form value
console.log(this.form.getRawValue())
}
// add the relevant interface for `product` array
populateProductForm(products: Array<any>): void {
products.forEach((product) => {
this.form.get('product')?.addControl(x.name, new FormControl(''))
})
}
CodePudding user response:
Try this:
ngOnInit() {
const productFormGroup = new FormGroup({});
this.products.forEach(product => productFormGroup.addControl(product.name, new FormControl('')));
this.form = this.fb.group({
SelectAll: new FormControl(''),
genericTextBox: new FormControl(''),
dateRangeTO: new FormControl('', [Validators.required]),
dateRangeFrom: new FormControl('', [Validators.required]),
products: productFormGroup,
});
console.log(this.form.value);
}
CodePudding user response:
We can create dynamic formControl name using bracket notation
Try this:
constructor(private fb: FormBuilder) {
const groupProducts = this.products.reduce((acc, product) => {
acc[product.name] = new FormControl('');
return acc;
}, {});
this.form = this.fb.group({
SelectAll: new FormControl(''),
genericTextBox: new FormControl(''),
dateRangeTO: new FormControl('', [Validators.required]),
dateRangeFrom: new FormControl('', [Validators.required]),
products: this.fb.group({
...groupProducts,
}),
});
}