我I have this snippet。我想做的是,当我按All NonTrades
时,所有要检查的a, b, c, d
都将被检查。与All Trades
一样,我希望aa, bb, cc, dd
被全部选中。
如何处理这种情况?谢谢您的时间!
答案 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 }
];
然后,选中“所有交易者”或“所有非交易者”复选框后,您可以对allNonTrades
和allTrades
方法进行修改。
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>
<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>
</ng-container>
<br>
<label class="btn btn-filter">
<input type="checkbox" name="allTrades" [value]="trade" (change)="allTrades($event)">All Trades
</label>
<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>
</ng-container>
这是您推荐的Working StackBlitz。