Angular2.0+開發 -實現部門樹形結構

在Angular2+中如何實現一個多層級的樹結構呢?css

首先想到的是用Ztree插件,或者用js遞歸生成樹的層級關係。html

若是要用Ztree,首先得引入第三方插件如JQuery,Ztree的相關js,css等,很是繁瑣,棄之。json

那麼另一種思路遞歸組合樹的層級關係,在Angular中對應的方法就是嵌套。安全

如下示例是在Angular2+中經過一個JSON數據(如ztree的json格式)生成部門樹結構app

先來看看效果圖spa

 


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,做爲數據集合。code

 

2.對於的html模板  dept-tree-area.component.htmlcomponent

<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...htm

     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": []     }     ]   } }];

相關文章
相關標籤/搜索