Bhrungarajni
Bhrungarajni

Reputation: 2535

how to keep the checkbox checked if it has been already checked using Angular2

I have a input checkbox field, when i check the box the functions work fine but after refresh the tick mark disappears in the box. So can i get the tick mark be true if it has been already selected and the data saved in other page.

HTML:

<td><input type="checkbox" [(ngModel)]="pin.checked" (change)="fav(pin)" style="margin-top: 10px;"></td>

TS:

loadAllPins() {
  var favouratePins = this.storage.favouratePins; 
  console.log(favouratePins);
  this.ApiService
      .getAllPins(this.guide_id)
      .subscribe(
        pins  => {
          if(favouratePins && favouratePins.length > 0) {
            pins.data.map(function(pin) {
              favouratePins.map(function(item) {
                if(pin._id == item._id) {
                  pin.checked = true;
                }
              })
            })            
          }
          this.pins = pins.data;

        },error => {
          console.log(error);
        });
}

in the first page what all i have checked had been and saved in another page, so the items which have been stored already in another page contents needs to be marked checked in the first page

Upvotes: 0

Views: 194

Answers (2)

Sravan
Sravan

Reputation: 18647

From your question you are sending pin_id as data to api so, you need to compare pin_id instead of _id

Here you are sending pin_id var data = { "user_id":user_id, "pin_id":pin._id }

So you should use,

 if(favouratePins && favouratePins.length > 0) {
    pins.data.map(function(pin) {
      favouratePins.map(function(item) {
       if(pin._id == item._id) {
            pin.checked = true;
        }
       })
      })            
     }
     this.pins = pins.data;
 }

Upvotes: 1

Anshuman Jaiswal
Anshuman Jaiswal

Reputation: 5462

You will have to add checked attribute.

<td>
   <input type="checkbox" [checked]="pin.checked" [(ngModel)]="pin.checked" (change)="fav(pin)" style="margin-top: 10px;">
</td>

Upvotes: 1

Related Questions