角度树视图

问题描述 投票:0回答:2

你好,

我正在使用 Angular 4,也许你现在可以称我为新手。 我在谷歌上搜索树视图,发现了两个非常好的框架。 First 和 ng2-tree(无法发布链接,没有足够的声誉;()。 但对于它们两个,我在创建新节点时遇到了问题。

第一个添加方法是正常编写的,但我不知道如何将节点添加到树的选定部分。

第二个添加方法写得有点奇怪,我不知道如何修复它。添加节点时,它会在视觉上添加,但不会添加到数组中(或者我们称其为树)。我确实尝试在添加方法上执行 push() ,但我无法获得与树数组相同的对象,然后,当我尝试将其作为 json 导入到 firebase 时,它给了我一个错误。

这个是针对 ng2-treeview 的。我尝试使用的方法是 onNodeCreated()

import { Component, Input, ViewEncapsulation, OnInit } from '@angular/core';
import { NodeEvent, TreeModel, RenamableNode, Ng2TreeSettings } from 'ng2-tree';
import { ServerService } from "app/pages/components/components/treeView/storeService.service";
import alertify from 'alertify.js';
import { Http, Response } from "@angular/http";
declare const alertify: any;
@Component({
  selector: 'tree-view',
  styleUrls: ['treeView.css'],
  templateUrl: 'treeView.html',
  providers: [ServerService],
  encapsulation: ViewEncapsulation.None
})

export class TreeView implements OnInit {
    constructor(private serverService: ServerService, private http: Http /*private treeview: TreeModel*/){
    }
    tree: TreeModel = {
    value: 'Programming languages by programming paradigm',
    children: [
      {
        value: 'Object-oriented programming',
        children: [
          {
            // I am a RenamableNode. Yeah, that's me :)
            value: <RenamableNode>{
              name: 'Java',
              setName(name: string): void {
                this.name = name;
              },
              toString(): string {
                return this.name;
              }
            }
          },
          {value: 'C++'}
        ]
      },
      {
        value: 'Prototype-based programming',
        settings: {
          'static': true
        },
        loadChildren: (callback) => {
          setTimeout(() => {
            callback([
              {value: 'JavaScript'},
              {value: 'CoffeeScript'},
              {value: 'TypeScript'}
            ]);
          }, 5000);
        }
      }
    ]
  };

    ngOnInit(){
        this.http.get('https://testing-angular-50890.firebaseio.com/data.json').map(
            (response: Response) => {
                const data = response.json();
                this.tree = data;
            }
        );
    }
    private static logEvent(e: NodeEvent, message: string): void {
        console.log(e);
        alertify.logPosition("top right");
        if((message==="Moved") || (message==="Renamed") || (message==="Created") || (message==="Selected")){
            alertify.success(`${message}: ${e.node.value}`);
        }
        else{
            alertify.error(`${message}: ${e.node.value}`);
        }

    }
    public onNodeRemoved(e: NodeEvent): void {
        TreeView.logEvent(e, 'Removed');
        this.http.put('https://testing-angular-50890.firebaseio.com/data.json', this.tree).subscribe(
            (response) => console.log(response),
            (error) => console.log(error)
        );
    }

    public onNodeMoved(e: NodeEvent): void {
        TreeView.logEvent(e, 'Moved');
        this.http.put('https://testing-angular-50890.firebaseio.com/data.json', this.tree).subscribe(
            (response) => console.log(response),
            (error) => console.log(error)
        );
    }

    public onNodeRenamed(e: NodeEvent): void {
        TreeView.logEvent(e, 'Renamed');
        this.http.put('https://testing-angular-50890.firebaseio.com/data.json', this.tree).subscribe(
            (response) => console.log(response),
            (error) => console.log(error)
        );
    }

    public onNodeCreated(e: NodeEvent): void {
        TreeView.logEvent(e, 'Created');
        console.log(e);
        this.tree.children.push(e.node);
        console.log(this.tree);
        this.http.put('https://testing-angular-50890.firebaseio.com/data.json', this.tree).subscribe(
            (response) => console.log(response),
            (error) => console.log(error)
        );
    }

    public onNodeSelected(e: NodeEvent): void {
        this.http.put('https://testing-angular-50890.firebaseio.com/data.json', this.tree).subscribe(
            (response) => console.log(response),
            (error) => console.log(error)
        );
        TreeView.logEvent(e, 'Selected');
        console.log(this.tree.children);
    }
}

错误信息 这是我上面提到的添加错误 enter image description here

**这是另一个,它没有给出任何错误,我只是不知道如何在这里开发添加方法。就像,我想在选定的节点上添加节点,但在本示例中,它仅在一个(硬编码)节点上添加**

import { Component, Input } from '@angular/core';
import { TreeNode, TreeModel, TREE_ACTIONS, KEYS, IActionMapping, ITreeOptions } from 'angular-tree-component';

const actionMapping:IActionMapping = {
  mouse: {
    contextMenu: (tree, node, $event) => {
      $event.preventDefault();
      alert(`context menu for ${node.data.name}`);
    },
    dblClick: (tree, node, $event) => {
      if (node.hasChildren) TREE_ACTIONS.TOGGLE_EXPANDED(tree, node, $event);
    },
    click: (tree, node, $event) => {
      $event.shiftKey
        ? TREE_ACTIONS.TOGGLE_SELECTED_MULTI(tree, node, $event)
        : TREE_ACTIONS.TOGGLE_SELECTED(tree, node, $event)
    }
  },
  keys: {
    [KEYS.ENTER]: (tree, node, $event) => alert(`This is ${node.data.name}`)
  }
};

@Component({
  selector: 'app-fulltree',
  styles: [
    `button: {
        line - height: 24px;
        box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.5);
        border: none;
        border-radius: 2px;
        background: #A3D9F5;
        cursor: pointer;
        margin: 0 3px;
      }`
  ],
  template: `
  <form>
    <input #filter (keyup)="filterNodes(filter.value, tree)" placeholder="filter nodes"/>
  </form>
  <div style="height: 400px; width: 300px">
    <tree-root
      #tree
      [nodes]="nodes"
      [options]="customTemplateStringOptions"
      [focused]="true"
      (event)="onEvent($event)"
      (initialized)="onInitialized(tree)"

    >
      <ng-template #treeNodeTemplate let-node>
        <span title="{{node.data.subTitle}}">{{ node.data.name }}</span>
        <span class="pull-right">{{ childrenCount(node) }}</span>
        <button (click)="go($event)">Custom Action</button>
      </ng-template>
      <ng-template #loadingTemplate>Loading, please hold....</ng-template>
    </tree-root>
  </div>
  <br>
  <p>Keys:</p>
  down | up | left | right | space | enter
  <p>Mouse:</p>
  click to select | shift+click to select multi
  <p>API:</p>
  <button (click)="tree.treeModel.focusNextNode()">next node</button>
  <button (click)="tree.treeModel.focusPreviousNode()">previous node</button>
  <button (click)="tree.treeModel.focusDrillDown()">drill down</button>
  <button (click)="tree.treeModel.focusDrillUp()">drill up</button>
  <button (click)="customTemplateStringOptions.allowDrag = true">allowDrag</button>
  <p></p>
  <button
    [disabled]="!tree.treeModel.getFocusedNode()"
    (click)="tree.treeModel.getFocusedNode().toggleActivated()">
    {{ tree.treeModel.getFocusedNode()?.isActive ? 'deactivate' : 'activate' }}
  </button>
  <button
    [disabled]="!tree.treeModel.getFocusedNode()"
    (click)="tree.treeModel.getFocusedNode().toggleExpanded()">
    {{ tree.treeModel.getFocusedNode()?.isExpanded ? 'collapse' : 'expand' }}
  </button>
  <button
    [disabled]="!tree.treeModel.getFocusedNode()"
    (click)="tree.treeModel.getFocusedNode().blur()">
    blur
  </button>
  <button
    (click)="addNode(tree)">
    Add Node
  </button>
  <button
    (click)="activateSubSub(tree)">
    Activate inner node
  </button>
  <button
    (click)="tree.treeModel.expandAll()">
    Expand All
  </button>
  <button
    (click)="tree.treeModel.collapseAll()">
    Collapse All
  </button>
  <button
    (click)="activeNodes(tree.treeModel)">
    getActiveNodes()
  </button>
  `
})
export class FullTreeComponent {
  nodes: any[];
  nodes2 = [{name: 'root'}, {name: 'root2'}];
  constructor() {
  }
  ngOnInit() {
    setTimeout(() => {
      this.nodes = [
        {
          expanded: true,
          name: 'root expanded',
          subTitle: 'the root',
          children: [
            {
              name: 'child1',
              subTitle: 'a good child',
              hasChildren: false
            }, {
              name: 'child2',
              subTitle: 'a bad child',
              hasChildren: false
            }
          ]
        },
        {
          name: 'root2',
          subTitle: 'the second root',
          children: [
            {
              name: 'child2.1',
              subTitle: 'new and improved',
              uuid: '11',
              hasChildren: false
            }, {
              name: 'child2.2',
              subTitle: 'new and improved2',
              children: [
                {
                  uuid: 1001,
                  name: 'subsub',
                  subTitle: 'subsub',
                  hasChildren: false
                }
              ]
            }
          ]
        },
        {
          name: 'asyncroot',
          hasChildren: true
        }
      ];

      for(let i = 0; i < 4; i++) {
        this.nodes.push({
          name: `rootDynamic${i}`,
          subTitle: `root created dynamically ${i}`,
          children: new Array((i + 1) * 100).fill(null).map((item, n) => ({
            name: `childDynamic${i}.${n}`,
            subTitle: `child created dynamically ${i}`,
            hasChildren: false
          }))
        });
      }
    }, 1);
  }

  asyncChildren = [
    {
      name: 'child2.1',
      subTitle: 'new and improved'
    }, {
      name: 'child2.2',
      subTitle: 'new and improved2'
    }
  ];

  getChildren(node:any) {
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve(this.asyncChildren.map((c) => {
        return Object.assign({}, c, {
          hasChildren: node.level < 5
        });
      })), 1000);
    });
  }

  addNode(tree) {
    this.nodes[0].children.push({

      name: 'a new child'
    });
    tree.treeModel.update();
  }

  childrenCount(node: TreeNode): string {
    return node && node.children ? `(${node.children.length})` : '';
  }

  filterNodes(text, tree) {
    tree.treeModel.filterNodes(text);
  }

  activateSubSub(tree) {
    // tree.treeModel.getNodeBy((node) => node.data.name === 'subsub')
    tree.treeModel.getNodeById(1001)
      .setActiveAndVisible();
  }

  customTemplateStringOptions: ITreeOptions = {
    // displayField: 'subTitle',
    isExpandedField: 'expanded',
    idField: 'uuid',
    getChildren: this.getChildren.bind(this),
    actionMapping,
    nodeHeight: 23,
    allowDrag: (node) => {
      // console.log('allowDrag?');
      return true;
    },
    allowDrop: (node) => {
      // console.log('allowDrop?');
      return true;
    },
    useVirtualScroll: true,
    animateExpand: true,
    animateSpeed: 30,
    animateAcceleration: 1.2
  }
  onEvent(event) {
    console.log(event);
  }

  onInitialized(tree) {
    // tree.treeModel.getNodeById('11').setActiveAndVisible();
  }

  go($event) {
    $event.stopPropagation();
    alert('this method is on the app component');
  }

  activeNodes(treeModel) {
    console.log(treeModel.activeNodes);
  }
}
javascript angular web treeview
2个回答
0
投票

0
投票

响应 - 您可以尝试 Syncfusion 的 Angular TreeView 控件,具有拖放、复选框支持等功能。

这是帮助您开始添加节点的文档

Syncfusion 为个人开发者和小型企业提供免费社区许可证

注:我为 Syncfusion 工作

© www.soinside.com 2019 - 2024. All rights reserved.