Issue
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": "",
}
}
Solution
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);
}
Answered By - Siddhant
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.