Bhrungarajni
Bhrungarajni

Reputation: 2525

How to keep the checkbox checked, even after other checkboxes checked using angular2

i have list of users and it gives checked for already shared user, now if i check on any one of the checkbox then the already checked one gets unchecked. please anyone help me to sort this issue.

HTML:

<div *ngFor="let contact of userList">

              <input  type="checkbox" name="radio" (click)="selectCheckboxInvitee($event.target.checked, contact, false)"
                [(ngModel)]="contact.isChecked" [disabled]="contact.isDisabled" />
              <a>{{ contact.FirstName }} &nbsp;{{ contact.LastName }}</a>
            </div>

Ts:

 selectCheckboxInvitee(evt, contact, isMultiple) {
    if (evt) {

      if (!isMultiple) {
        this.userList.forEach(function (obj) {
          if (obj.Id === contact.Id) {
            obj.isChecked = true;
          }
          else {
            obj.isChecked = false;
          }
        });

      }

    }
  }

  getSharedIds(sPk) {
  //  this.dicom.getSharedIDs(sPk).subscribe(res => {
  //    if (res.Body) {
        const inviteeIds = this.res
          ? this.res.split(",")
          : [];
        this.userList.forEach(r => {
          r.isChecked = false;
        //  r.isDisabled = false;
          if (inviteeIds) {
            inviteeIds.forEach(i => {
              if (i == r.Id) {
                r.isChecked = true;
                r.isDisabled = true;
              }
            });
          }
        });
      }

DEMO: Please Find Demo here

Upvotes: 0

Views: 63

Answers (2)

penleychan
penleychan

Reputation: 5470

Check if object is not disabled

 selectCheckboxInvitee(evt, contact, isMultiple) {
    if (evt) {

      if (!isMultiple) {

        this.userList.forEach(function (obj) {
          if(!obj.isDisabled) {
            if (obj.Id === contact.Id) {
              obj.isChecked = true;
            }
            else {
              obj.isChecked = false;
            }
         }
      });
    }
  }   
}

stackblitz: https://stackblitz.com/edit/angular-zz3zg5

Alternatively you can use filter:

this.userList.filter(u => !u.isDisabled).forEach(function (obj) {
  if (obj.Id === contact.Id) {
    obj.isChecked = true;
  }
  else {
    obj.isChecked = false;
  }
});

Upvotes: 2

Sebastian Oleński
Sebastian Oleński

Reputation: 538

Well it behaves exactly the way you wrote the code. I can see that you have a method selectCheckboxInvitee that takes an argument called isMultiple in your binding.

Just change this in your html:

selectCheckboxInvitee($event.target.checked, contact, false)

to

selectCheckboxInvitee($event.target.checked, contact, true)

and it's going to let you select multiple checkboxes

Upvotes: 0

Related Questions