Angular2.0+开发 -实现部门树形结构

在Angular2+中如何实现一个多层级的树结构呢?

首先想到的是用Ztree插件,或者用js递归生成树的层级关系。

如果要用Ztree,首先得引入第三方插件如JQuery,Ztree的相关js,css等,非常繁琐,弃之。

那么另外一种思路递归组合树的层级关系,在Angular中对应的方法就是嵌套。

以下示例是在Angular2+中通过一个JSON数据(如ztree的json格式)生成部门树结构

先来看看效果图

 


1.创建树组件  dept-tree-area.component.ts

import { Component, OnInit,Input } from '@angular/core';

@Component({
  selector: 'app-dept-tree-area',
  templateUrl: './dept-tree-area.component.html',
  styleUrls: ['./dept-tree-area.component.css']
})
export class DeptTreeAreaComponent implements OnInit {
  //接收上级的值
  @Input() treelists: any
 
  constructor() { }

  ngOnInit() {

  }
}

 这里添加了一个入口参数treelists,作为数据集合。

 

2.对于的html模板  dept-tree-area.component.html

<ul class="ng-scope">
  <li *ngFor="let item of treelists" class="ng-scope">
    <a class="{{item.deep==0 ? 'lvl rootNode' : 'lvl'+item.deep}}">
      <span class="expand-tree-icon">
        <i><img src="/assets/imgs/caret_down.png" /></i>
      </span>
      <span class="tree-icon">
        <img src="/assets/imgs/department_icon.png" class="department_icon" />
      </span>
      <span class="title">
        <span class="title-text ng-binding">{{item.name}}</span>
      </span>
    </a>
    <!--调用组件本身并 传值给下级: [treelists]="item.items"-->
    <app-dept-tree-area *ngIf="item.open && item.children && item.children.length" [treelists]="item.children"></app-dept-tree-area>
  </li>
</ul>

  说明:2.1 样式:class="{{item.deep==0 ? 'lvl rootNode' : 'lvl'+item.deep}} 根据层级设置样式缩进,根样式为lvl rootNode,一级目录为lvl1,二级目录样式为lvl2...

     2.2 <app-dept-tree-area ...[treelists]="item.children"></app-dept-tree-area>:如果有子级,则嵌套子级模板

3.调用

 

在其他组件通过<app-dept-tree-area></app-dept-tree-area>调用

如dept-tree.component.html中

 

  <app-dept-tree-area *ngIf="menuTreeJson && menuTreeJson.length" [treelists]="menuTreeJson"></app-dept-tree-area>

 

 在dept-tree.component.ts中对menuTreeJson就行赋值

menuTreeJson =[{

  "id": "d001",
  "name": "A公司",
  "open": true,
  "deep": 0,
  "children": [
  {
    "id": "d002",
    "name": "售前部",
    "open": true,
    "deep": 1,
    "children": []
  },
  {
    "id": "d003",
    "name": "销售部",
    "open": true,
    "deep": 1,
    "children": [
    {
      "id": "d003001",
      "name": "销售总监",
      "open": true,
      "deep": 2,
      "children": []
    }
    ]
  },
  {
    "id": "d004",
    "name": "安全事业部",
    "open": true,
    "deep": 1,
    "children": []
    },
    {
    "id": "d005",
    "name": "系统部",
    "open": true,
    "deep": 1,
    "children": []
  },
  {
    "id": "d009",
    "name": "开发部",
    "open": true,
    "deep": 1,
    "children": [
    {
      "id": "d009001",
      "name": "项目组",
      "open": true,
      "deep": 2,
      "children": []
    },
    {
      "id": "d009002",
      "name": "产品组",
      "open": true,
      "deep": 2,
      "children": []
    }
    ]
  }
}
];

 

posted @ 2017-09-28 15:13  齐大齐  阅读(2758)  评论(4编辑  收藏  举报