PrimeNG Tree v16 with checkbox selection: How to achieve programmatic single selection?

255 views Asked by At

I'm working with the PrimeNG Tree component in Angular, specifically with selectionMode set to "checkbox". I want to achieve a programmatic single selection.

In other words, I want to ensure that selecting a child node automatically unselects all other child and parent nodes except the one directly associated with the selected child node.

I have the following code in my Angular component where I am trying to deselect all the nodes before selecting the new one. But it is not working as expected. Previously selected parent nodes remain selected.

export class TreeCheckboxDemo implements OnInit {
  files!: TreeNode[];
  selectedFiles!: TreeNode[];

  constructor(private nodeService: NodeService) {}

  ngOnInit() {
    this.nodeService.getFiles().then((data) => (this.files = data));
  }

  public onNodeSelect(event: any) {
    if (this.selectedFiles.length > 1) {
      this.selectedFiles = null;
    }
    this.selectedFiles = [event.node];
  }
}

I've created a StackBlitz example to provide more context. Any help or code examples would be greatly appreciated. Thank you!

1

There are 1 answers

2
Naren Murali On

This may not help you, but the reasons you are getting this problem is because all the nodes do not have a common parent, if you can define a common parent, this issue will resolve, because the uncheck if propogated, but since there is no common parent, the emit is not reaching all the other nodes!

Here is my partial atempt to fix the issue, hope it helps you!

stackblitz