Angular2 push values to array on checkbox selected

2019-09-06 17:50发布

问题:

I have a set of checkboxes as following:

<div class="mdl-grid">
    <div class="mdl-cell mdl-cell--4-col">
        <label #checkbox_1 class="mdl-checkbox mdl-js-checkbox" for="checkbox-1">
            <input type="checkbox" id="checkbox-1" name="hobbies" value="sport" 
            class="mdl-checkbox__input">
            <span class="mdl-checkbox__label">Sports</span>
        </label>
        <label #checkbox_2 class="mdl-checkbox mdl-js-checkbox" for="checkbox-2">
            <input type="checkbox" id="checkbox-2" name="hobbies" value="reading" class="mdl-checkbox__input">
            <span class="mdl-checkbox__label">Reading</span>
        </label>
    </div>
    <div class="mdl-cell mdl-cell--4-col">

        <label #checkbox_3 class="mdl-checkbox mdl-js-checkbox" for="checkbox-3">
            <input type="checkbox" id="checkbox-3" name="hobbies" value="singing"  
            class="mdl-checkbox__input">
            <span class="mdl-checkbox__label">Singing</span>
        </label>
        <label #checkbox_4 class="mdl-checkbox mdl-js-checkbox" for="checkbox-4">
            <input type="checkbox" id="checkbox-4" name="hobbies" value="travelling" 
            class="mdl-checkbox__input">
            <span class="mdl-checkbox__label">Travelling</span>
        </label>
    </div>
    <div class="mdl-cell mdl-cell--4-col">
        <label #checkbox_5 class="mdl-checkbox mdl-js-checkbox" for="checkbox-5">
            <input type="checkbox" id="checkbox-5" name="hobbies" value="movies"  
            class="mdl-checkbox__input">
            <span class="mdl-checkbox__label">Movies</span>
        </label>
        <label #checkbox_6 class="mdl-checkbox mdl-js-checkbox" for="checkbox-6">
            <input type="checkbox" id="checkbox-6" name="hobbies" value="cooking" 
            class="mdl-checkbox__input">
            <span class="mdl-checkbox__label">Cooking</span>
        </label>
    </div>
</div>

In my component I have an array:

hobbies: string[];

constructor(){
  this.hobbies=[];
} 

I would like to collect all the values which user has checked the checkbox in this array i.e. hobbies=['sport', 'reading'..]. How can I do that?

回答1:

I would just use ngModel:

hobbies = {};

constructor() {
}

getHobbies() {
    return Object.entries(this.hobbies).filter(arr => arr[1]).map(arr => arr[0]);
}

And in the view:

  <label><input type="checkbox" [(ngModel)]="hobbies['sport']"/>Sport</label>
  <label><input type="checkbox" [(ngModel)]="hobbies['cooking']"/>Cooking</label>
  <label><input type="checkbox" [(ngModel)]="hobbies['cinema']"/>Cinema</label>

  <br>
  Hobbies: 
  <ul>
    <li *ngFor="let hobby of getHobbies()">{{ hobby }}</li>
  </ul>

Here's a plunkr illustrating it.



标签: angular