Angular material branch node selection mode – prevent value combining

I have an angular material tree in selection mode and I want to achieve what this vue library achieves https://vue-treeselect.js.org/#prevent-value-combining

So in the list of selection in the end I need just the branch node if all leaf nodes are selected otherwise use all leaf nodes.

Is there an easy way of doing this, some configuration that you can pass to the mat tree component to achieve this?

I tried writing a method that will be called whenever a node is selected/deselected and deal with all the cases, but I have a 4 level tree and this is clearly code hell.

setSelectedNode(node: AssetNode) {
    const descendants = [];
    Utils.getDescendantsOfNode(node, descendants);
    if(node.isChecked) {
      if (descendants.length) {
        this.selectedNodes = this.selectedNodes.filter(n => !descendants.some(child => child.id === n.id));
      }
      if(!this.selectedNodes.map(n => n.id).includes(node.id)) this.selectedNodes.push(node);
    } else {

      if (descendants.length) {
        this.selectedNodes = this.selectedNodes.filter(n => !descendants.some(child => child.id === n.id));
      }

      if (node.parent) {
        if(Utils.descendantsPartiallySelected(node.parent)) {
          this.selectedNodes = this.selectedNodes.filter(selectedNode => selectedNode.id !== node.parent.id && selectedNode.isChecked);
          const nodesToSelect = node.parent.children.filter(child => child.isChecked);
          nodesToSelect.forEach(nodeToAdd => {
            if (!this.selectedNodes.map(s => s.id).includes(nodeToAdd.id)) {
              this.selectedNodes.push(nodeToAdd);
            }
          })
        }
      }
      this.selectedNodes = this.selectedNodes.filter(selectedNode => selectedNode.id !== node.id);
    }

    console.log(this.selectedNodes)
    this.allSelectedNodes.next(this.selectedNodes);
  }

Source: Angular Material Quesions