Search code examples
angulartypescriptionic-frameworkionic2ionic3

Pick the all checked items from the component - Multi select Check box


I have 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
        },

]

Solution

  • 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; }));