如何从角度5的嵌套树中删除节点?

时间:2018-09-05 13:57:13

标签: angular tree

此代码将用于创建嵌套的树结构。我也能够添加子节点。我被迫删除当前节点及其子节点。 如何在单击“删除”按钮时删除当前节点及其子节点 如何在同一级别添加新节点

 
    @Component({
          selector: 'tree-node'
          template: `
          <div>{{node.name}} <button(click)="addNewNode(node)">Add</button> <button (click)="removeNode(node)">Remove</button></div>
          <ul>
            <li *ngFor="let node of node.children">
              <tree-node  [node]="node"></tree-node>
            </li>
          </ul>
        `})

  export class TreeNode {
          @Input() node;
    addNewNode(node) {
        const newNode = {name: 'newNode', children: []};
        node.children.push(newNode);

   }

    removeNode(node) {
    node.children = [] // this code will remove only its child node
    }
}
         @Component({
          selector: 'my-app',
          providers: [],
          template: `
            <div>
              <h2>Hello {{name}}</h2>
              <tree-node [node]="node"></tree-node>
            </div>
          `,
          directives: [TreeNode]
        })
        export class App {
          constructor() {
            this.name = 'Angular2 (Release Candidate!)'
          }

          node = {name: 'root', children: [
            {name: 'a', children: []},
            {name: 'b', children: []},
            {name: 'c', children: [
              {name: 'd', children: []},
              {name: 'e', children: []},
              {name: 'f', children: []},
             ]},
          ]};  
        }

1 个答案:

答案 0 :(得分:0)

您可以在Angular 6材质嵌套树中找到添加,删除和更新操作 Angular 6 Material Nested Tree is not working with dynamic data