I am building a dynamic form using Angular 6. Please find here https://stackblitz.com/edit/angular6-dynamic-form-ovyftx
But on submit not getting form values in proper format. I am getting like
{"group1":{"brave":"","firstName":"Bombasto","emailAddress":"","multiBox":""},"group2":{"brave":"","firstName":"Bombasto","emailAddress":"","multiBox":""}}
I should get like
{"group1":{"brave":"","firstName":"Bombasto"},"group2":{"emailAddress":"","multiBox":""}}
Because fields belong to different group. How to fix this? Also how can i validate form on group basis. like if one field is invalid , that group should get a red border.
You did a small mistake on your service question-control.service. You are adding the new control to the same variable "group". so on the second loop, your previous controls are also added to it. Just reset its value on next loop. You are good to go for your first problem.
Object.keys(questions).forEach((eachgroup: string) => {
group = {}; //here you new to reset the value of group
questions[eachgroup].forEach(question => {
group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
: new FormControl(question.value || '');
});
sections[eachgroup] = new FormGroup(group);
});
And for the validation part, you can use [ngClass] directive and apply your custom css for invalid input like below:
<div [formGroup]="form" [ngClass]="{'isa_error':isValid?false:true}">
<label [attr.for]="question.key">{{question.label}}</label>
....
</div>
Working Code Example:https://stackblitz.com/edit/angular6-dynamic-form-wvspuw
App: https://angular6-dynamic-form-wvspuw.stackblitz.io
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With