Thinker
Thinker

Reputation: 5356

Angular2 ngFor get only selected values

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.

Upvotes: 0

Views: 1186

Answers (2)

Haem
Haem

Reputation: 929

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).

Upvotes: 0

Vivek Doshi
Vivek Doshi

Reputation: 58593

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);
    }
}

Upvotes: 3

Related Questions