Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 dynamic form with multiple form group

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.

like image 371
Pritam Parua Avatar asked Jun 23 '26 22:06

Pritam Parua


1 Answers

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

like image 83
Amir Avatar answered Jun 26 '26 15:06

Amir