如何在Angular 5的Kendo UI TreeView中添加自定义图标?
在Angular 5 Kendo TreeView节点两侧添加自定义图标的实现方法
我之前在做Angular 5项目时也碰到过这个需求,刚好可以给你分享下具体的实现方法,分左侧和右侧图标两种情况来说:
一、给节点左侧添加自定义图标(用iconClass)
Kendo TreeView的iconClass属性确实可以用来绑定自定义图标类,具体步骤如下:
准备自定义图标样式
先在全局样式文件(比如styles.css)里定义你的图标类,不管是用背景图还是字体图标都可以:/* 背景图方式 */ .custom-folder-icon { background-image: url('./assets/icons/folder.svg'); width: 16px; height: 16px; display: inline-block; background-size: contain; background-repeat: no-repeat; margin-right: 8px; } /* 字体图标方式(如果用自定义字体或第三方字体) */ .custom-file-icon { font-family: 'YourCustomFont'; content: '\e001'; color: #4285F4; margin-right: 8px; }在节点数据中配置
iconClass字段
给你的TreeView数据源添加iconClass属性,绑定上面定义的样式类:import { Component } from '@angular/core'; @Component({ selector: 'app-tree-view', templateUrl: './tree-view.component.html' }) export class TreeViewComponent { public treeNodes: any[] = [ { text: '项目文档', iconClass: 'custom-folder-icon', items: [ { text: '需求说明书', iconClass: 'custom-file-icon' }, { text: '设计文档', iconClass: 'custom-file-icon' } ] }, { text: '代码仓库', iconClass: 'custom-folder-icon', items: [ { text: '前端代码', iconClass: 'custom-file-icon' } ] } ]; }在模板中绑定TreeView
直接在模板里使用[nodes]和textField绑定数据,iconClass会自动生效:<kendo-treeview [nodes]="treeNodes" textField="text"></kendo-treeview>
二、给节点右侧添加自定义图标(用节点模板)
iconClass默认只处理左侧图标,如果要在右侧加自定义图标,需要用Kendo TreeView的节点模板来自定义内容:
修改数据源,添加右侧图标类字段
在节点数据里新增一个字段(比如rightIconClass)用来绑定右侧图标样式:public treeNodes: any[] = [ { text: '项目文档', iconClass: 'custom-folder-icon', rightIconClass: 'custom-edit-icon', items: [ { text: '需求说明书', iconClass: 'custom-file-icon', rightIconClass: 'custom-delete-icon' } ] } ];定义右侧图标样式
同样在样式文件里添加右侧图标的类:.custom-edit-icon { background-image: url('./assets/icons/edit.svg'); width: 14px; height: 14px; display: inline-block; background-size: contain; background-repeat: no-repeat; cursor: pointer; } .custom-delete-icon { background-image: url('./assets/icons/delete.svg'); width: 14px; height: 14px; display: inline-block; background-size: contain; background-repeat: no-repeat; cursor: pointer; }使用节点模板自定义节点结构
在模板里用kendoTreeViewNodeTemplate来改写节点的HTML结构,把右侧图标加进去:<kendo-treeview [nodes]="treeNodes" textField="text"> <ng-template kendoTreeViewNodeTemplate let-item> <!-- 用flex布局让文本和右侧图标左右分开 --> <div class="tree-node-content"> <span class="k-icon" [ngClass]="item.iconClass"></span> <span class="node-text">{{ item.text }}</span> <!-- 右侧图标 --> <span class="right-icon" [ngClass]="item.rightIconClass"></span> </div> </ng-template> </kendo-treeview>添加布局样式
给自定义的节点容器加样式,确保布局正确:.tree-node-content { display: flex; align-items: center; justify-content: space-between; width: 100%; padding: 4px 0; } .node-text { flex: 1; margin: 0 8px; }
一些注意事项
- 确保图标文件放在Angular的
assets目录下,路径要写对,比如./assets/icons/xxx.svg - 如果使用字体图标,记得先在
angular.json的styles数组里导入字体的CSS文件,或者在全局样式里@import - Angular 5对应的Kendo UI版本是
@progress/kendo-angular-treeview的早期版本,模板语法是完全兼容的,不用担心版本问题
内容的提问来源于stack exchange,提问作者Spoorti
相关产品推荐
相关产品推荐

