How to save selected checkbox as an array in ionic

Viewed 291

I have a simple form where I have the list of checkboxes and I want to send only the checked boxes to the typescript, but when I click on the save button then I face an error {test: undefined}

This is my form:

<ion-content>
  <ion-item *ngFor="let manager of managers; let i = index">
    <ion-checkbox
      color="primary"
      [(ngModel)]="manager.id"
      value="{{manager.id}}"
      style="margin-right: 10px"
    ></ion-checkbox>
    <ion-label>{{manager.name}}</ion-label>
  </ion-item>

  <ion-button (click)="save()">Save</ion-button>
</ion-content>

And this is my typescript:

  manager:any;
  constructor(private http: HttpClient) {}

  save(){
    let data ={
      test: this.manager,
    }
    console.log(data);
  }

So, basically, I want that the checked boxes value should be stored in array TS.

Thanks in advance.

1 Answers

first of all you can get rid of the value tag inside your checkbox. [(ngModel)] should create the selected entry in the object if it is selected after that. You need to check the array when the button is pushed to see if the element has a selected element AND(!) if it's true (checked).

After that you can store the value of the selected manager object in an array.

<ion-item *ngFor="let manager of managers; let i = index">
    <ion-checkbox
      color="primary"
      [(ngModel)]="manager.selected"
      style="margin-right: 10px"
    ></ion-checkbox>
    <ion-label>{{manager.name}}</ion-label>
  </ion-item>
Related