Angular2.0+开发 -实现部门树形结构
在Angular2+中如何实现一个多层级的树结构呢?
首先想到的是用Ztree插件,或者用js递归生成树的层级关系。
如果要用Ztree,首先得引入第三方插件如JQuery,Ztree的相关js,css等,非常繁琐,弃之。
那么另外一种思路递归组合树的层级关系,在Angular中对应的方法就是嵌套。
以下示例是在Angular2+中通过一个JSON数据(如ztree的json格式)生成部门树结构
先来看看效果图
1.创建树组件 dept-tree-area.component.ts
这里添加了一个入口参数treelists,作为数据集合。
2.对于的html模板 dept-tree-area.component.html
说明: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中
在dept-tree.component.ts中对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": []
}
]
}
}
];