Issue
My form has dynamic controls. This is how I defined them:
form = this._formBuilder.group({
services: this._formBuilder.array([])
});
const servicesFormArray = this.form.get('services') as FormArray;
for (let service of quotation.services) {
const serviceFormGroup = this._formBuilder.group({
[service.serviceName]: this._formBuilder.control(false)
});
servicesFormArray.push(serviceFormGroup);
}
console.log(this.form)
gives me the following result:
My goal is to simplify the form controls and to get rid of 0: FormGroup
and the second controls
. So I want to the structure to be like this:
- controls
- services
- controls
- My Product
I also tried it this way:
const servicesFormArray = this.form.get('services') as FormArray;
for (let service of quotation.services) {
const serviceFormGroup = this._formBuilder.group({
[service.serviceName]: this._formBuilder.control(false)
});
const serviceControl = serviceFormGroup.get(service.serviceName);
servicesFormArray.push(serviceControl);
}
But then I get this structure:
- controls
- services
- controls
- [0]
How can I achieve the desired structure?
Solution
Instead of formArray
, we can just set a formGroup
and then use addControl
method to add the individual form values!
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
@Component({
selector: 'app-root',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<h1>Hello from {{ name }}!</h1>
<a target="_blank" href="https://angular.dev/overview">
Learn more about Angular
</a>
`,
})
export class App {
name = 'Angular';
form = this._formBuilder.group({
services: this._formBuilder.group({}),
});
quotation = {
services: [
{
serviceName: 'test',
},
{
serviceName: 'test1',
},
{
serviceName: 'test2',
},
],
};
constructor(private _formBuilder: FormBuilder) {}
ngOnInit() {
const servicesFormArray = this.form.get('services') as FormGroup;
for (let service of this.quotation.services) {
servicesFormArray.addControl(
service.serviceName,
this._formBuilder.control(false)
);
}
console.log(this.form);
}
}
bootstrapApplication(App);
Answered By - Naren Murali
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.