Skip to content

Commit

Permalink
fix: set group as selected when all children selected
Browse files Browse the repository at this point in the history
  • Loading branch information
varnastadeus committed Aug 28, 2018
1 parent 763712c commit 8afda25
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
17 changes: 15 additions & 2 deletions src/ng-select/items-list.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,21 @@ describe('ItemsList', () => {
list.select(list.items[1]); // K1
list.select(list.items[2]); // K2

expect(list.filteredItems.length).toBe(3); // should contain only second group items
expect(list.selectedItems.length).toBe(2);
expect(list.filteredItems.length).toBe(3);
});

it('should select group when all group children are selected', () => {
cmp.hideSelected = true;
cmp.groupBy = 'groupKey';
list.setItems([
{ label: 'K1', val: 'V1', groupKey: 'G1' },
{ label: 'K2', val: 'V2', groupKey: 'G1' },
]);
list.select(list.items[1]); // K1
list.select(list.items[2]); // K2

expect(list.selectedItems.length).toBe(1);
expect(list.selectedItems[0].label).toBe('G1');
});

it('should remove all group and group children items if group is selected when hideSelected=true', () => {
Expand Down
15 changes: 10 additions & 5 deletions src/ng-select/selection-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,18 @@ export class SelectionModel {
this._selected.push(item);
if (multiple) {
if (item.parent) {
this._removeParent(item.parent);
const childrenCount = item.parent.children.length;
const selectedCount = item.parent.children.filter(x => x.selected).length;
item.parent.selected = childrenCount === selectedCount;
if (item.parent.selected) {
this._removeChildren(item.parent);
this._selected = [...this._selected, item.parent];
} else {
this._removeParent(item.parent);
}
} else if (item.children) {
this._setChildrenSelectedState(item.children, true);
this._removeParentChildren(item);
this._removeChildren(item);
}
}
}
Expand All @@ -30,12 +35,12 @@ export class SelectionModel {
if (item.parent && item.parent.selected) {
const children = item.parent.children;
this._removeParent(item.parent);
this._removeParentChildren(item.parent);
this._removeChildren(item.parent);
this._selected.push(...children.filter(x => x !== item));
item.parent.selected = false;
} else if (item.children) {
this._setChildrenSelectedState(item.children, false);
this._removeParentChildren(item);
this._removeChildren(item);
}
}
}
Expand All @@ -48,7 +53,7 @@ export class SelectionModel {
children.forEach(x => x.selected = selected);
}

private _removeParentChildren(parent: NgOption) {
private _removeChildren(parent: NgOption) {
this._selected = this._selected.filter(x => x.parent !== parent);
}

Expand Down

0 comments on commit 8afda25

Please sign in to comment.