Skip to content

Instantly share code, notes, and snippets.

@trungvose
Last active March 11, 2021 03:54
Show Gist options
  • Save trungvose/596c1e0fcaee2c2d02d67672fdbaff57 to your computer and use it in GitHub Desktop.
Save trungvose/596c1e0fcaee2c2d02d67672fdbaff57 to your computer and use it in GitHub Desktop.
Abstract class for handling selected items
export interface ICheckBoxModel {
checked: boolean;
}
export class CheckboxesSinglePageModel<T extends ICheckBoxModel> {
items: T[];
isSelectAll: boolean;
isIndeterminate: boolean;
constructor(items: T[], initialState = false) {
this.items = items;
this.updateSelectAllState();
if (initialState) {
this.setAllItemState(initialState);
}
}
get itemCount(): number {
return this.items.length;
}
get hasItems(): boolean {
return !!this.itemCount
}
get selectedItems() {
return this.items.filter(x => x.checked);
}
get selectItemsCount(): number {
return this.selectedItems.length;
}
onCheckboxClick(e: MouseEvent) {
e.stopPropagation();
}
onItemChange() {
this.updateSelectAllState();
}
selectAll(toggleSelectAll = false) {
if (toggleSelectAll) {
this.isSelectAll = !this.isSelectAll;
}
this.setAllItemState(this.isSelectAll);
}
setAllItemState(isCheck: boolean) {
this.items.forEach(item => item.checked = isCheck);
this.updateSelectAllState();
}
updateSelectAllState() {
this.isSelectAll = this.items.length === this.selectedItems.length;
this.isIndeterminate = !this.isSelectAll && !!this.selectedItems.length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment