Sampath
Sampath

Reputation: 65870

Pick the all checked items from the component - multi-select checkbox

I have a multi-select checkbox list as shown below. Can you tell me how to pick the all checked items from the component (.ts)?

.html:

<ion-list>
        <ion-item *ngFor="let i of inputs">
          <ion-label>{{i.display}}</ion-label>
          <ion-checkbox name="{{i.label}}" [(ngModel)]="i.checked"></ion-checkbox>
        </ion-item>
</ion-list>

.ts:

this.inputs=[
        {
            "encode": "1",
            "display": "en falls asleep without a caregiver in the room",
            "label": "uiFallsAsleepUnassistedBedTime",
            "checked": false
        },
        {
            "encode": "2",
            "display": "During breastfeeding",
            "label": "uiBreastFeedBedTime",
            "checked": false
        },
        {
            "encode": "3",
            "display": "Being rocked or held (in arms or baby sling/carrier)",
            "label": "uiSlingBedTime",
            "checked": false
        },
        {
            "encode": "4",
            "display": "In motion (stroller, car, etc.)",
            "label": "uiInMotionBedTime",
            "checked": false
        },

]

Upvotes: 0

Views: 763

Answers (2)

Roman C
Roman C

Reputation: 1

If you have a model item state checked variable then you can add a binding to the attribute

<ion-checkbox name="{{i.label}}" [(ngModel)]="i.encode" [checked]="i.checked" (change)="change(i, $event)"></ion-checkbox>

.ts code:

  checked = [];

  change(item, event) {
    var index = this.inputs.map(i => i.encode).indexOf(item.encode);
    if(event.target.checked) {
      if(index === -1) {
        this.checked.push(item);
      }
    } else {
      if(index !== -1) {
        this.checked.splice(index, 1);
      }
    }

  }

Upvotes: 0

Pengyy
Pengyy

Reputation: 38171

OP's Feedback: Below one is working for me.

this.inputs.filter(opt => opt.checked).map(opt => opt.label);

Original Answer:

I think you should bind i.checked instead of i. encode to ion-checkbox. and then you can use Array.filter to get the checked items.

var inputs = [{
    "encode": "1",
    "display": "en falls asleep without a caregiver in the room",
    "label": "uiFallsAsleepUnassistedBedTime",
    "checked": false
  },
  {
    "encode": "2",
    "display": "During breastfeeding",
    "label": "uiBreastFeedBedTime",
    "checked": true
  },
  {
    "encode": "3",
    "display": "Being rocked or held (in arms or baby sling/carrier)",
    "label": "uiSlingBedTime",
    "checked": false
  },
  {
    "encode": "4",
    "display": "In motion (stroller, car, etc.)",
    "label": "uiInMotionBedTime",
    "checked": true
  },
]

console.log(inputs.filter(function(item){ return item.checked === true; }));

Upvotes: 2

Related Questions