Skip to content

Instantly share code, notes, and snippets.

@subrothosamantha
Created August 9, 2024 11:11
Show Gist options
  • Save subrothosamantha/6afd6e39de96c28ec1b016ff9e15af13 to your computer and use it in GitHub Desktop.
Save subrothosamantha/6afd6e39de96c28ec1b016ff9e15af13 to your computer and use it in GitHub Desktop.
TreeSelect: Custom Workaround for Programmatic Selection
export const CUSTOM_TREESELECT_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomTreeSelectComponent),
multi: true
};
interface TreeNodeEvent {
originalEvent: Event;
node: TreeNode<any>;
children: [];
key: string;
}
@Component({
selector: 'cx-custom-treeselect',
templateUrl: './custom-treeselect.component.html',
styleUrls: ['./custom-treeselect.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
providers: [CUSTOM_TREESELECT_VALUE_ACCESSOR],
encapsulation: ViewEncapsulation.None
})
export class CustomTreeSelectComponent extends TreeSelect implements AfterContentInit {
iconTypes = ICON_TYPE;
listId: string = '';
@Input() ariaLabel: string | undefined;
@Input() isParentVisible: boolean = true;
nodes: any;
override writeValue(value: any): void {
if (value != null) {
this.value = this.getNodesFromOptions(value, this.options);
this.nodes = this.isParentVisible ? this.value : this.removeParentSelection(this.value);
this.checkParentIfChildrenSelected(this.options);
this.cd.markForCheck();
}
}
getNodesFromOptions(nodesToFind: any[], options: TreeNodeEvent[]): any[] {
let nodes: any[] = [];
nodesToFind.forEach((nodeToFind) => {
options.forEach((option) => {
if (option.key === nodeToFind.key) {
nodes.push(option);
}
if (option.children && option.children.length > 0) {
nodes = nodes.concat(this.getNodesFromOptions([nodeToFind], option.children));
}
});
});
return nodes;
}
checkParentIfChildrenSelected(nodes: TreeNodeEvent[]): void {
nodes.forEach((node: any) => {
if (node.children && node.children.length > 0) {
this.checkParentIfChildrenSelected(node.children);
const allChildrenSelected = node.children.every((child: any) => {
return this.value.some((selectedNode: any) => selectedNode.key === child.key);
});
const partialChildrenSelected = node.children.some((child: any) => {
return this.value.some((selectedNode: any) => selectedNode.key === child.key) || child.partialSelected;
});
node.partialSelected = partialChildrenSelected && !allChildrenSelected;
if (allChildrenSelected && !this.value.some((selectedNode: any) => selectedNode.key === node.key)) {
this.value.push(node);
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment