Search code examples
angularcheckboxtreeangular-materialcheckboxtree

Angular material tree checkbox with real example


I've seen almost all examples about how to work with angular material tree checkbox component. for example official example and this.
these examples show us a string array structure as a data was bonded. but how can we transform a nested complex object array to this component?

My data structure:

enter image description here

As you can see the data says to the client which items of the checkbox must be set as ticked. and 'Id' must be bind to the tree.

When I replace my 'TREE-DATA' with official example 'TREE-DATA', I see the following tree as result.
I suppose we need to change 'buildFileTree()' or 'transformer()' methods in official example. enter image description here

Angular(7.0.0), Angular Material(6.4.7)


Solution

  • Finally I solved this problem and I wrote a sample in this place

    How the problem was solved?
    I did some changes in 'buildFileTree()' and 'transformer()' methods. you can see the changes in the following code:

    buildFileTree(obj: {[key: string]: any}, level: number): TodoItemNode[] {
    return Object.keys(obj).reduce<TodoItemNode[]>((accumulator, key) => {
      const item = obj[key];
      const node = new TodoItemNode();
      node.label = obj[key].name;
      node.id = obj[key].id;
      node.isChecked=  obj[key].isChecked;
      node.claimId=  obj[key].claimId;
      node.isPlanType=  obj[key].isPlanType;
    
      if (item != null) {
        if (typeof item === 'object'  && item.children!= undefined) { 
    
    
          node.children = this.buildFileTree(item.children, level + 1);
        } else {
          node.label = item.name;
        }
      }
    
      return accumulator.concat(node);
    }, []);}
    
      transformer = (node: TodoItemNode, level: number) => {
    const existingNode = this.nestedNodeMap.get(node);
    const flatNode = existingNode && existingNode.label === node.label
        ? existingNode
        : new TodoItemFlatNode();
    flatNode.label = node.label;
    flatNode.level = level;
    flatNode.id=node.id;
     flatNode.isChecked = node.isChecked;
     flatNode.claimId = node.claimId;
     flatNode.isPlanType = node.isPlanType;
    flatNode.expandable = !!node.children;
    this.flatNodeMap.set(flatNode, node);
    this.nestedNodeMap.set(node, flatNode);
    return flatNode;  }