When working with real world applications, it’s often required to render a tree like structure. Say a tree view of directories in a file system or a finely categorized list of items. Something like this.

list-blokk-png-706x699Let’s create one for ourselves using Angular 2.

For the sake of brevity, I have omitted common import statements and other boilerplate code.

The Idea

It’s pretty simple. To parse infinite trees, we do recursion. To do that, we call a function within that function until a breaking condition is met.

The same idea works for templates. We render our component, within the same component and let it do the same till the tree meets it’s leaf nodes.

Skeleton App & Data

Here’s how our App component looks like.

The code is pretty simple.

  • We include <ui-tree>  component in our app template. We’ll see the detailed code for <ui-tree>  in a moment.
  • We have key  which is the property name in our data that increases the depth of the tree. In our case, data  is an array of objects and each object contains name  and categories  array. This categories  array is what gives depth to our tree. So key  here is “categories”.

UI Tree Component

Below is what the tree component itself looks like. It accepts two parameters, the data  and the key . It then calls itself in the template and passes the inner categories  array to render another sub-tree.

Key thing to notice in this code is recursive inclusion of the  <ui-tree>  component in the template.

Putting Things Together…