Search code examples
angularionic3ngforion-checkbox

How to set Ngmodel for a nested ngFor ion-checkbox?


I have a nested ngFor Checkbox.. All i need is to set the NgModel to check if the check box is checked??

<ion-item-group *ngFor="let patient of Patients; let i= index">
<ion-item-divider color="light">{{patient.conditionGroup}}</ion-item-divider>
<ion-item *ngFor="let condition of patient.conditions; let j= index">
<ion-label>{{condition}}</ion-label>
<ion-checkbox id="{{condition}}" [(ngModel)]="checkStatus[i][j]" (ionChange)="mylist(i,j,condition)" color="danger"></ion-checkbox>
</ion-item>
</ion-item-group>

my controller is like this..

  {
    this.checkStatus=[];
    this.Patients = [];

    for(var s=0;s<this.Patients.length;s++)
    {this.checkStatus[s]=[];}
    }

How do i check if the checkbox is checked.. error
    ERROR TypeError: Cannot read property '0' of undefined

Patients

[
      {
        "conditionGroup": "Family Care",
        "conditions": [
          "Head",
          "Poisoning",
          "Stroke"
        ]
      }
]

in myList() i need to push the checked options into an array..


Solution

  • Code for Controller

    import { Component } from '@angular/core';
    import { NavController } from 'ionic-angular';
    
    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {
      checkStatus = [];
      Patients = [];
    
      constructor(public navCtrl: NavController) {
    
        this.initPatients();
      }
    
      initPatients(){
         this.Patients = [
          {
            "conditionGroup": "Family Care",
            "conditions": [
              "Head",
              "Poisoning",
              "Stroke"
            ]
          },
          {
            "conditionGroup": "Family Care",
            "conditions": [
              "Head",
              "Poisoning",
              "Stroke"
            ]
          },
          {
            "conditionGroup": "Family Care",
            "conditions": [
              "Head",
              "Poisoning",
              "Stroke"
            ]
          }
        ];
         this.updateStatus();
      }
      updateStatus() {
        for (var s = 0; s < this.Patients.length; s++)
        { this.checkStatus[s] = []; }
      }
    
    
    
    }
    

    Code for Html

    <ion-header>
      <ion-navbar>
        <ion-title>Home</ion-title>
      </ion-navbar>
    </ion-header>
    
    <ion-content padding>
     <ion-item-group *ngFor="let patient of Patients; let i= index">
    <ion-item-divider color="light">{{patient.conditionGroup}}</ion-item-divider>
    <ion-item *ngFor="let condition of patient.conditions; let j= index">
    <ion-label>{{condition}}</ion-label>
    <ion-checkbox id="{{condition}}" [(ngModel)]="checkStatus[i][j]" (ionChange)="mylist(i,j,condition)" color="danger"></ion-checkbox>
    </ion-item>
    </ion-item-group>
    </ion-content>