0

I have a for loop that populates pre-defined hobbies as checkboxes. hobbies = ['Sport', 'Reading', 'Singing', 'Travelling', 'Movies', 'Cooking'];

<label *ngFor="let hobby of chunk" #checkbox class="mdl-checkbox mdl-js-checkbox">
    <input type="checkbox" name="hobbies" [value]="hobby" 
    [(ngModel)]="hobby.selected" (change)="populateMyHobbies(hobby)" class="mdl-checkbox__input">
    <span class="mdl-checkbox__label">{{hobby}}</span>
</label>

I have created an array my_hobbies: string[]=[]; in which I want to collect only the selected values i.e. ['Sport',..]

My function that collects those values is so far:

populateMyHobbies(value){

    this.my_hobbies.push(value)
    console.log(this.my_hobbies)
}   

How can I achieve this? Right now on check and uncheck the values get added even same value multiple times.

Thinker
  • 4,664
  • 9
  • 48
  • 119

2 Answers2

3

Template side :

<label *ngFor="let hobby of chunk" #checkbox class="mdl-checkbox mdl-js-checkbox">
    <input type="checkbox" name="hobbies" [value]="hobby" 
    [(ngModel)]="hobby.selected" (change)="populateMyHobbies(hobby,$event.target.checked)" class="mdl-checkbox__input">
    <span class="mdl-checkbox__label">{{hobby}}</span>
</label>

Component side :

selectedHobbies = [];

populateMyHobbies(value , status:boolean)
{
    if(this.selectedHobbies.indexOf(value) === -1 && status)
    {
        this.selectedHobbies.push(value);
    }
    else if(!status)
    {
        let index = this.selectedHobbies.indexOf(value);
        this.selectedHobbies.splice(index, 1);
    }
}
Vivek Doshi
  • 46,471
  • 9
  • 84
  • 100
0

You'll want to pass the check event as an argument to populateMyHobbies, and then read event.target.checked to check whether the checkbox is checked or unchecked (Like the answer here).

You can check whether the array contains a value by checking if array.indexOf(value) returns -1, and remove them with array.splice(index,1) (As in this answer).

Community
  • 1
  • 1
Haem
  • 879
  • 6
  • 13
  • 24