Basic Implementation

In order to implement the Material Tree, firstly we need to understand the concept of these two following important properties and how they are being implemented.

nestedDataSource

nestedTreeControl

The first property, nestedDataSource holds our Tree data and is responsible for toggling tree updates. The moment it receives a data source, connect() function is being triggered, which returns an observable that emits an array of data. Now, that the nestedDataSource is connected with the data source, whenever data are emitted from the data source, the tree is auto updated.

The second property, nestedTreeControl allows users to expand/collapse a tree node. Through the _getChlidren function it will recursively check the nodes for any Children; if there are any it may return an observable of children for a given node and enable its expansion. Thus far, piece of cake, right?

TypeScript

Additionaly, the HTML implementation is very simple.

Initially, we need to bind our nestedDataSource data with the [dataSource] property and nestedTreeControl with the [treeControl] property.

Afterwards we have to create two mat-tree-node elements:

one for the nodes that do not have Children

one for the nodes that do

Lastly, we need to loop through our data.

However, instead of using the *ngFor we use *matTreeNodeDef. In fact their functionality is pretty similar, with the only difference that now we take as data argument the expression that is bind to the [dataSource].

Since our data have been declared we use string interpolation to render them.

HTML

The final step is to implement the CSS classes in our css file.

CSS

Therefore, having everything set up we have the basic version of the material tree ready for usage.