Updated April 15, 2023
Introduction to Angular Material Tree
Angular material provides us with the way to create a tree, which is a structured data representation of our data. By this, we can represent the list or common set of values inside one tag only. Before this, we have cdk-tree which enables us to create this type of structure, and material directive is built on top of that, it basically provides us two types of tree structure one is flat and the other one is nested, flat can be viewed easy at they are at a single level only, but the nested one can have so many inside it as the list. Angular material provides us with the default styling and designing for this as well. Here we will see in detail how we can create this nested and flat type tree using angular material in our application to make the UI more interactive to the user, as well as for better clarity of its implementation.
Syntax of Angular Material Tree
Given below is the syntax for the tree in the material library.
<cdk-tree-node></cdk-tree-node>: this tag is used to get the leaf node
<cdk-tree-node></cdk-tree-node>: This tag is used to create the expandable nodes.
We will have to look at the configuration in detail which needs to make in order to run this tree structure properly. Also, we would require to have a lot of coding for this library to use in the project. We will take reference from the angular material documentation for example.
How to Create Tree in Angular Material?
As now we already know that to create the tree structure using material we are making use of cdk-tree, because it is built on top of that only, also it supports two types of tree structure one of them is flat and other one is nested tree.
Here we will see all the configuration that is required to make this work.
1. CdkTreeModule
This is the module which we need to import inside the root module or any of the child min which we want to display the tree, for reference follow the below code and copy this into your root module.
Example:
import {CdkTreeModule} from '@angular/cdk/tree';
2. cdk-nested-tree-node
It is the child of cdk-node, if you want to create the child on the parent node, and also some nested structure that is a list of the list then we can make use of this directive, tag ‘cdk-nested-tree-node’ can be used to create this type of structure in the indie the parent node.
3. It has some of the properties as mentioned below:
- Level: It represents the number of levels we have.
- isExpanded: It takes an Boolean as the value if the parent node has the child or not to represent this.
- Data: It is the data itself which we want to show.
Steps that need to be taken in order to step up our angular material project initially.
1. First install the angular CLI which enables us to download the required packages and library for our project. You can download it by typing the below command on your command to make sure you have already installed the node.
Example:
npm install -g @angular/cli)
The above command will install the CLI globally in our system hence we can use it globally when required.
2. Now in this step we will try to create the new angular project from scratch, this project will not be a material project that we have to add later by installing the material dependency inside our project. so just execute the below command on your Command Prompt and press enter.
Example:
ng new your project name
>> ng new my-first-project
This command will create the project with the name my-first-project, you can create your project with any name mentioned.
3. Just to make sure try one command which is mentioned below to install all the required libraries into our project.
Example:
npm install
4. Now you can test and run your project by typing the simple command which is mentioned below. This is just to make sure that we are on the right track and our project has been created without any error or bugs inside it.
Example:
ng serve
5. Go on browser and try to run the application with the below URL:
http://localhps:4200
By default, the angular project runs on the port 4200, you can change it as per your need if required.
6. Now everything is set we have our angular project now we will add the material library to our project just by running the below command on the command prompt.
Example:
ng add @angular/material
Example of Angular Material Tree
Given below is the example mentioned:
index.html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons&display=block" rel="stylesheet">
<title>Demo tree material</title>
</head>
<body class="mat-app-background">
<tree-demo>Loading .. </tree-demo>
<span class="version-info">Current build: 12.1.1</span>
</body>
</html>
module.ts code:
import {NgModule} from '@angular/core';
import {CdkStepperModule} from '@angular/cdk/stepper';
import {CdkTableModule} from '@angular/cdk/table';
import {CdkTreeModule} from '@angular/cdk/tree';
@NgModule({
exports: [
CdkStepperModule,
CdkTableModule,
CdkTreeModule,
]
})
export class DemoMaterialModule {}
demo.tree.component.ts code:
import {ArrayDataSource} from '@angular/cdk/collections';
import {FlatTreeControl} from '@angular/cdk/tree';
import {Component} from '@angular/core';
const MY_TREE_DATA: TreeDemo[] = [
{
name: 'Options',
expandable: true,
level: 0,
}, {
name: 'One',
expandable: false,
level: 1,
}, {
name: 'Two',
expandable: false,
level: 1,
}, {
name: 'Three',
expandable: true,
level: 1,
}, {
name: 'Four',
expandable: true,
level: 1,
}
, {
name: 'Five',
expandable: true,
level: 1,
}
, {
name: 'Six',
expandable: true,
level: 1,
}
];
interface TreeDemo {
expandable: boolean;
name: string;
level: number;
isExpanded?: boolean;
}
/**
* @title Tree demo using material
*/
@Component({
selector: 'tree-demo',
templateUrl: 'demo.tree.component.html',
styleUrls: ['demo.tree.component.css'],
})
export class DemoTreeMaterial {
treeControl = new FlatTreeControl<TreeDemo>(
node => node.level, node => node.expandable);
dataSource = new ArrayDataSource(MY_TREE_DATA);
hasChild = (_: number, node: TreeDemo) => node.expandable;
getMyParentNode(node: TreeDemo) {
const nodeIndex = MY_TREE_DATA.indexOf(node);
for (let i = nodeIndex - 1; i >= 0; i--) {
if (MY_TREE_DATA[i].level === node.level - 1) {
return MY_TREE_DATA[i];
}
}
return null;
}
shouldRender(node: TreeDemo) {
let parent = this.getMyParentNode(node);
while (parent) {
if (!parent.isExpanded) {
return false;
}
parent = this.getMyParentNode(parent);
}
return true;
}
}
demo.tree.component.html code:
<h5><u><i>Tree using angular material !!</i></u></h5>
<cdk-tree [dataSource]="dataSource" [treeControl]="treeControl">
<cdk-tree-node *cdkTreeNodeDef="let node" cdkTreeNodePadding
[style.display]="shouldRender(node) ? 'flex' : 'none'"
class="example-tree-node">
<button mat-icon-button disabled></button>
{{node.name}}
</cdk-tree-node>
<cdk-tree-node *cdkTreeNodeDef="let node; when: hasChild" cdkTreeNodePadding
[style.display]="shouldRender(node) ? 'flex' : 'none'"
class="example-tree-node">
<button mat-icon-button cdkTreeNodeToggle
[attr.aria-label]="'Toggle ' + node.name"
(click)="node.isExpanded = !node.isExpanded"
[style.visibility]="node.expandable ? 'visible' : 'hidden'">
<mat-icon class="mat-icon-rtl-mirror">
{{treeControl.isExpanded(node) ? 'expand_more' : 'chevron_right'}}
</mat-icon>
</button>
{{node.name}}
</cdk-tree-node>
</cdk-tree>
Output:
Conclusion
By the use of this, we can represent our data in the form of tree node structure, but it is not very easy and direct to use, we have to make configurations in order to use this in our application, also a lot of coding is required on the s and html component, this requires a basic understanding of is in prior to use it properly.
Recommended Articles
We hope that this EDUCBA information on “Angular Material Tree” was beneficial to you. You can view EDUCBA’s recommended articles for more information.