Angular2将值推送到选中的复选框上的数组

时间:2017-04-02 08:51:08

标签: angular

我有一组复选框如下:

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

在我的组件中,我有一个数组:

hobbies: string[];

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

我想收集用户检查此数组中复选框的所有值,即hobbies = ['sport','reading'..]。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

我只想使用ngModel:

hobbies = {};

constructor() {
}

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

在视图中:

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

这里是plunkr illustrating it