选中所有具有相同名称的复选框

时间:2018-11-09 10:25:51

标签: html angular

I have this snippet。我想做的是,当我按All NonTrades时,所有要检查的a, b, c, d都将被检查。与All Trades一样,我希望aa, bb, cc, dd被全部选中。

如何处理这种情况?谢谢您的时间!

1 个答案:

答案 0 :(得分:1)

您需要一个Object数组而不是String Array来保留选中了哪个复选框的记录:

nontrade = [
  { label: 'a', selected: false }, 
  { label: 'b', selected: false }, 
  { label: 'c', selected: false }, 
  { label: 'd', selected: false }
];

trade = [
  { label: 'aa', selected: false }, 
  { label: 'bb', selected: false }, 
  { label: 'cc', selected: false }, 
  { label: 'dd', selected: false }
];

然后,选中“所有交易者”或“所有非交易者”复选框后,您可以对allNonTradesallTrades方法进行修改。

allNonTrades(event) {
  const checked = event.target.checked;
  this.nontrade.forEach(item => item.selected = checked);
}

allTrades(event) {
  const checked = event.target.checked;
  this.trade.forEach(item => item.selected = checked);
}

最后,您必须将模板中的属性绑定的value更改为checked

<label class="btn btn-filter">
  <input type="checkbox" name="allNonTrades" [value]="nontrade" (change)="allNonTrades($event)">All NonTrades
</label>&nbsp;
<ng-container *ngFor="let ntrd of nontrade">
  <label class="btn btn-filter">
    <input type="checkbox" name="nontrades" [checked]="ntrd.selected" (change)="changeTradesByCategory($event)">{{ ntrd.label }}
  </label>&nbsp;
</ng-container>

<br>

<label class="btn btn-filter">
  <input type="checkbox" name="allTrades" [value]="trade" (change)="allTrades($event)">All Trades
</label>&nbsp;
<ng-container *ngFor="let trd of trade">
  <label class="btn btn-filter">
    <input type="checkbox" name="trades" [checked]="trd.selected" (change)="changeTradesByCategory($event)">{{ trd.label }}
  </label>&nbsp;
</ng-container>

这是您推荐的Working StackBlitz