Recursion in Angular components

Oct 27, 2020 10:01 · 147 words · 1 minute read angular

How to create tree like structures based on recursion in Angular.

On occassion we will need to use recursion to display some data (e.g. nested array structures). Luckily Angular components can be called from their own template. Let us try it out:

Simple recursion component

This is basic recursion at work - we call component in its own template until we reach 0.

More complex example - nested arrays

The most practical example is nested array structures that should be presented in Tree like structure. Here we check if current level is array or just item (string in our example). If it is array we loop over items and for each item render its own component. If we have just a string we show it in template.

Stackblitz demo for this example:

Recursion in Angular components on Stackblitz

Additional reading

For a more complex solution and in detail explanation - a great article : Reusable Tree view Component