1
votes

I have a scenario where configuration comes from the server, means the form is generated by the config from the server; like input type, label etc. So, the text field, checkbox, select option, and the radio button is built dynamically by the server response.

But when the checkbox has multiple values (eg: js, PHP, python) I can't get that right. Cause I have created formControl in a loop so doesn't matter how many options in checkbox, I always get a single output from checkbox form control. I have tried formArray but can't quite get the result I want.

// ts    

const group = {};
this.category.header.forEach(input => {
  group[input.id] = new FormControl('');
});
this.myFormGroup = new FormGroup(group);

// html

<form [formGroup]="myFormGroup" (ngSubmit)="onSubmit()">
  <div *ngFor="let form_elem of category.header">
  <div [ngSwitch]="form_elem.type">
    <div *ngSwitchCase="'text'">
      <input type="text" formControlName="{{form_elem.id}}"/>
    </div>
    <div *ngSwitchCase="'radio'">
        <div *ngFor="let item of form_elem.options">
            <input type="radio" [value]='item' formControlName="{{form_elem.id}}" >
        </div>
    </div>
    <div *ngSwitchCase="'select'">
      <select formControlName="{{form_elem.label}}">
        <option *ngFor="let opt of form_elem.options">
          {{opt}}
        </option>
      </select>
    </div>
    <div *ngSwitchCase="'checkbox'">
        <div *ngFor="let item of form_elem.options">
            <input type="checkbox" [value]='item' formControlName="{{form_elem.id}}">
        </div>
    </div>
  </div>  
</div>
  <input type="submit" value="save"/>
</form>

I am expecting my checkbox property would be like

checkbox: [{option1: true}, {option2: false} ]

1
@kuklyy this.category.header is an array of objects for instance, one element of this array would be like bellow: { id: "some_id", label: "input_label" options: ['js', 'php', 'node'] type: "checkbox" } - Mohammad Tanveruzzaman
can you add a minimal reproduction exemple ? on stackblitz or ... - bubbles

1 Answers

0
votes

You can try these way, but you need to check somewhere condition for checkbox

    this.category.header.forEach(input => {
        if(input.type == 'checkbox'){
            let opts = {};
            for (let opt of input.options) {
                opts[opt.key] = new FormControl(opt.value);
            }
            group[input.id] = new FormGroup(opts)
        }else{
            group[input.id] = new FormControl('');
        }
    });