Get dynamic icon in Angular Treeview component
28 Sep 20233 minutes to read
In TreeView component, you can get the original bound data using the getTreeData
method. For this method, if you pass the id of the tree node, it returns the corresponding node information, or otherwise the overall tree nodes information will be returned. You can use this method to get the bound iconCss class in the nodeChecking
event. Please refer to the following sample.
import { Component, Inject, ViewChild } from '@angular/core';
import { NodeCheckEventArgs, TreeViewComponent } from '@syncfusion/ej2-angular-navigations';
/**
* Icon css sample
*/
@Component({
selector: 'app-container',
template: `<div id='treeparent'><ejs-treeview id='treeElement' #treevalidate [fields]='field' (nodeChecking)='onNodeCheck($event)' [showCheckBox]=true [autoCheck]=false></ejs-treeview></div>`
})
export class AppComponent {
// Data source for TreeView component
public treeData: Object[] = [
{
"nodeId": "01", "nodeText": "Music", "icon": "folder", "expanded": true, "nodeChild": [
{ "nodeId": "01-01", "nodeText": "Gouttes.mp3", "icon": "audio" }
]
},
{
"nodeId": "02", "nodeText": "Videos", "icon": "folder", "expanded": true, "nodeChild": [
{ "nodeId": "02-01", "nodeText": "Naturals.mp4", "icon": "video" },
{ "nodeId": "02-02", "nodeText": "Wild.mpeg", "icon": "video" }
]
}
];
public field:Object ={ dataSource: this.treeData, id: 'nodeId', text: 'nodeText', child: 'nodeChild', iconCss: 'icon', expanded: 'expanded' };
@ViewChild ('treevalidate') tree?: TreeViewComponent;
public onNodeCheck(args: NodeCheckEventArgs): void {
let nodeId: any = args.data[0]['id'];
// To get the iconCss
let iconClass = this.tree?.getTreeData(nodeId)[0]['icon'];
alert('Icon class is ' + iconClass);
}
}
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { TreeViewModule } from '@syncfusion/ej2-angular-navigations';
/**
* Module
*/
@NgModule({
imports: [
BrowserModule,FormsModule,TreeViewModule
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';
enableProdMode();
platformBrowserDynamic().bootstrapModule(AppModule);