如何检查Angular 6中的所有先前的复选框

时间:2018-08-14 09:48:46

标签: angular checkbox input

当我单击一个复选框时,我想选中所有上一个复选框,然后取消选中所有下一个复选框,我怎么能做到这一点?

这是我生成复选框的方式

<div *ngFor="let check of feature.tests; let i = index" class="col-md-12">
    <mat-checkbox>{{check.name}}</mat-checkbox>
</div>

编辑:使用jquery,我通过做类似的事情来实现

$('input[type="checkbox"]').on('click', function() {
  $(this).prevAll().prop('checked', true);
  $(this).nextAll().prop('checked', false);
});

2 个答案:

答案 0 :(得分:0)

您应该可以将change属性设置为mat-checkbox,类似这样

[i+str(j) for j in range(3) for i in a]
# OP ['a0', 'b0', 'c0', 'a1', 'b1', 'c1', 'a2', 'b2', 'c2']

其中checkboxChanged是打字稿中的一种方法:

<mat-checkbox (change)="checkboxChanged($event.checked, i)"></mat-checkbox>

答案 1 :(得分:0)

DEMO

HTML:

<div *ngFor="let check of feature; let i = index" class="col-md-12">
<mat-checkbox [checked]="i <= finalC" (change)="checkAll($event.checked, i)">{{check.name}}</mat-checkbox>

TS:

  finalC: number = -1;
  constructor() {
  }

  feature: Array<any> = [
    { name: 'checkbox 1' },
    { name: 'checkbox 2', },
    { name: 'checkbox 3', },
    { name: 'checkbox 4', }]

  checkAll(c, i: number) {

    if (c) {
      this.finalC = i
    } else {
      this.finalC = i - 1
    }
  }