【发布时间】:2019-07-01 12:34:54
【问题描述】:
我有一个项目列表及其关联的复选框。
我想实现以下目标:
- 使用“全选”复选框选择/取消选择列表中的所有项目。
- 选择/取消选择列表中的单个项目。
- 当所有项目都被选中并单击任何选定项目时,取消选中“全选”复选框。
这些步骤中的大部分都按预期工作,除了我:
- 通过选中“全选”复选框来选择所有列表项
- 取消选中任何选定的项目
- 然后再次选中“全选”复选框。
这会导致我在单击“全选”复选框之前未选中的任何列表项保持未选中状态。
在这种情况下,看起来(由于某种原因)复选框的内部状态没有改变。
虽然,当:
- 所有列表项都未选中,我选择了任何列表项
- 然后选中“全选”复选框
它正确选择了所有列表项。所以我有点困惑为什么它在上面提到的其他情况下不起作用。
注意:我不想为列表中的每个项目存储状态的主要原因是我将在带有虚拟滚动的表中使用它。它逐页获取数据。所以我无法访问所有项目数据,因此,我只存储我手动选择或未选择的项目。
app.component.ts
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent {
constructor( private cdr: ChangeDetectorRef ) {
this.cdr.markForCheck();
}
public list = [
"item1", "item2", "item3", "item4", "item5"
];
public selected = {
ids: [],
all: false,
all_except_unselected: false
};
public toggleSelectItem( id: number, event: MouseEvent ): void {
if ( this.selected.all === true ) {
this.selected.all = false;
this.selected.all_except_unselected = true;
this.selected.ids = [];
}
if ( this.selected.all_except_unselected === true ){
this.selected.ids = [ ...this.selected.ids, id ];
} else if ( this.selected.all == false && this.selected.all_except_unselected == false ) {
if ( this.selected.ids.indexOf( id ) === -1 ) {
this.selected.ids = [ ...this.selected.ids, id ];
} else {
this.selected.ids = [ ...this.selected.ids].filter( itemId => itemId !== id );
}
}
console.log(this.selected.ids);
}
public isSelected( id: number ): boolean {
if ( this.selected.all === true ) {
console.log(id, 'selected all')
return true;
} else if ( this.selected.all_except_unselected === true ) {
console.log(id, 'selected all except unselected');
return true;
}
console.log(id, this.selected.ids.indexOf( id ) >= 0 ? 'selected' : 'unselected');
return this.selected.ids.indexOf( id ) >= 0;
}
public toggleSelectAll(): void {
if ( this.selected.all == false ) {
this.selected.ids = [];
}
this.selected.all = !this.selected.all;
this.selected.all_except_unselected = false;
console.log('selected all ', this.selected );
}
}
app.component.html
<input type="checkbox" [checked]="selected.all" (change)="toggleSelectAll()"> Select All
<br>
<br>
<div *ngFor="let item of list; let i = index" >
<input type="checkbox" [checked]="isSelected(i)" (change)="toggleSelectItem(i, $event)"> {{ item }}<br>
</div>
【问题讨论】:
-
请在问题本身中包含所有相关代码,而不仅仅是在外部网站上。见minimal reproducible example。您可以使用Stack Snippets 轻松完成此操作。
标签: javascript html angular checkbox