Search code examples
angulartypescriptangular-forms

ngform checkbox selection array submission


I have used a step wizard utilising ngform. After the a user clicks "next" and that saves locally the users selection until the form submits on the final step.

I have introduced checkboxes to step 1 of the form. I can build up an array of the new chosen checkboxes and I also get an array for he rest of the form. I have tried combining the two but my form model does not like it.

Here is a stackblitz of my efforts so far - https://stackblitz.com/edit/angular-j7cu3x

main Issue - you will notice in the stackblitz above that after step 1 is complete and the checkboxes have been selected the selection array remains empty.

html - checkbox

<div *ngFor="let selection of intelSelections; let i=index">
  <label class="form-check-label">
    {{selection}}
  </label>
  <input class="form-check-input" [ngModel]="isSelected(selection)" (ngModelChange)="onChange(selection, $event)" type="checkbox" name="intelgroup_{{i}}">
</div>

component.ts - checkbox logic

isSelected(value: string): boolean {
    return this.selectedIntel.indexOf(value) >= 0;
}

onChange(value: string, checked: boolean) {
    console.log(value, checked);
    if (checked) {
        this.selectedIntel.push(value);
    } else {
        let index = this.selectedIntel.indexOf(value);
        this.selectedIntel.splice(index, 1);
    }
}

SAVE step 1

save(form: any): boolean {
    this.formDataService.setPersonal(this.personal);
    return true;
}

this.personal is the other array of input data on the form that gets submitted.

I can see two options:

  1. combine this.selectedIntel to this.personal
  2. [ngModel]="isSelected(selection)" figure out how to add personal.selection to ngModel.

Solution

  • Update your save method to:

    save(form: any): boolean {
        this.personal.selection = this.selectedIntel;
        this.formDataService.setPersonal(this.personal);
        return true;
    }