angularprimengtreetable

Adding children to PrimeNg TreeTable programmatically


I'd like to add childNodes to a TreeTable programmatically. There's no problem adding the parent-nodes like:

var parentNode: TreeNode = { data: {
        'col1': 'aaa',
        'col2': 'aaa',
      }};

this.treeTableModel.push(parentNode);

But when I'm trying to do:

parentNode.children.push(childNode);

Children is undefined?

What's the best way to implement this?


Solution

  • first, you can look at TreeNode api here: https://github.com/primefaces/primeng/blob/bb1792eac98c7beb9d18ff68bed99408ad650108/components/common/api.ts

    second, you initialized parentNode like this

    var parentNode: TreeNode = { data: {
            'col1': 'aaa',
            'col2': 'aaa',
          }};
    

    parentNode has no property children at this point. You'll have to add it. children is a TreeNode array: TreeNode[] so what you can do is:

    var parentNode: TreeNode =
           { 
            data: {
              'col1': 'aaa',
              'col2': 'aaa',
             },
             children:[];
           };
    

    now that children is initialized as an empty array, you can push to it:

    this.treeTableModel.push(parentNode);