Angular2根据复选框的选定值更新对象数组

时间:2017-04-03 13:21:38

标签: angular

我有一个如下数组:

hobbies: any= [
    {'hobby': 'Sport', 'selected': false},
    {'hobby': 'Music', 'selected': false},
    {'hobby': 'Reading', 'selected': false},
    {'hobby': 'Travelling', 'selected': false},
    {'hobby': 'Movies', 'selected': false},
    {'hobby': 'Cooking', 'selected': false},
]

我在模板中迭代这个数组:

<span style="float: left; width: 100px;"><h5>Hobbies</h5></span>
<div class="mdl-grid">
    <div *ngFor="let chunk of hobbies | chunks: 2" class="mdl-cell mdl-cell--4-col">
        <label *ngFor="let hobby of chunk | values" #checkbox class="mdl-checkbox mdl-js-checkbox">
            <input type="checkbox" name="hobbies" [value]="hobby" 
            [(ngModel)]="hobby.selected" (change)="populateTest(hobby, $event.target.checked)" class="mdl-checkbox__input">
            <span class="mdl-checkbox__label">{{hobby.hobby}}</span>
        </label>
    </div>
</div>

我想要做的是:用户检查这些对象的值应该相应地在hobbbies[]数组中更新(现在我只是将它们推送到另一个数组中)。

如果selected:true中的任何值已标记为hobbies[],则复选标记应已在我的模板中显示。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

将您的代码更改为:

function validateDate($date, $format = 'Y-m-d H:i:s') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

检查变更值:

组件方:

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

某些Angular2版本更新不支持上述代码,请尝试运行此

consoleHobbies()
{
   console.log(this.hobbies);
}