Search code examples
angulartypescriptcheckboxangular2-mdl

Enable checkbox dynamically using angular2


I am trying to display a list of checkboxes using " *ngFor" attribute as follows.

 <mdl-list>
    <mdl-list-item *ngFor="let group of Groups">
      <mdl-list-item-primary-content>
        <mdl-checkbox mdl-ripple  (change)="onChanged($event,group.guid)" [(ngModel)]="isGroupChecked">{{group.group_name}}</mdl-checkbox>
      </mdl-list-item-primary-content>
      </mdl-list-item>
  </mdl-list>

In my component I have an asynchronous call to get a list of group id's whose checkboxes are to be enabled.After I get the result I am checking for a condition to check if the checkbox must be enabled.

I want to enable the checkbox after the condition is validated. ("at the comment mentioned in the method")

getUserGroupNames() {
  this.Groups.forEach(group => {
  this.userGroups.groups.forEach(user_group => {
  if (group.entity_group_guid == user_group.entity_group_guid) {
  console.log(group.entity_group_guid);

  //I want to enable the check box after this comparison.

   this.isGroupChecked = true;
  }
  });
  });
  }

I want to enable the checkbox after I compare the id's.

Please Help!

Thanks in advance.


Solution

  • You need to have isGroupChecked property for each item, instead of having Global isGroupChecked variable.

    <mdl-list>
    <mdl-list-item *ngFor="let group of Groups">
      <mdl-list-item-primary-content>
        <mdl-checkbox mdl-ripple  (change)="onChanged($event,group.guid)" [(ngModel)]="group.isGroupChecked">{{group.group_name}}</mdl-checkbox>
      </mdl-list-item-primary-content>
      </mdl-list-item>
    

    Component:

    getUserGroupNames() {
      this.Groups.forEach(group => {
      this.userGroups.groups.forEach(user_group => {
      if (group.entity_group_guid == user_group.entity_group_guid) {
        console.log(group.entity_group_guid);
        //need to have separate properties.
         group.isGroupChecked = true;
      }
     });
     });
    }
    

    Hope it helps!