Taoufik J
Taoufik J

Reputation: 800

Adding dynamically checked checkboxes values to a list

I'm displaying a list of preference as checkboxes, the problem reside in the binding part where i want a list of the ids that were checked. my try who does not work:

<div class="checkbox" *ngFor="let preference of preferences">
<label><input type="checkbox" value="{{preference.id}}" (change)="preferencesStates[i]=$event.target.value">{{preference.label}}</label>
</div>

This is how i bring the preferences:

this.reservationService.getPreferences().subscribe(preferences => {
  if (preferences) {
    JSON.parse(preferences.body).forEach(element => {
      this.preferences.push(element);
    });
  }
});

Upvotes: 1

Views: 1305

Answers (2)

Abrar
Abrar

Reputation: 7232

In the (change) event you can bind a function like this -

(change)="getInput($event)"

I would prefer to pass the index as well.

Now in your component class add the following code:

public resArray: any[] = [];  //for storing the checked ids

getInput(event: any,index:number) {
   if(event.target.checked){
      this.resArray.push(event.target.value);
    }else{
      this.resArray.splice(index,1);
    }
  }

Note here that you get both the checked and unchecked conditions.

Now the resArray will contain all the ids that were checked. Make sure you pass the index. So, your template code will look like this -

<div class="checkbox" *ngFor="let preference of preferences;let i=index">
<label><input type="checkbox" value="{{preference.id}}" (change)="getInput($event, i)">{{preference.label}}</label>
</div>

Upvotes: 2

Vivek Doshi
Vivek Doshi

Reputation: 58553

Change your code with this

<div class="checkbox" *ngFor="let preference of preferences; let i = index;">
<label><input type="checkbox" value="{{preference.id}}" (change)="preferencesStates[i]=$event.target.value">{{preference.label}}</label>
</div>

In this i is not defined anywhere , preferencesStates[i]

Another solution :

<div class="checkbox" *ngFor="let preference of preferences; let i = index;">
<label><input type="checkbox" value="{{preference.id}}" (change)="preferencesStates[preference.id]=$event.target.checked">{{preference.label}}</label>
</div>

Declare it as preferencesStates:any; in your component , this will give you list of all preferencesStates with id , checked as true and unchecked as false.

Upvotes: 1

Related Questions