Recursive Templates In Angular

Introduction 

 
Many times we come across templates in Angular where we have to recursively add UI components. For example, while creating a table of contents, there can be 0 or many sub-sections, as shown in the below picture:
 
Recursive Templates In Angular
 
To achieve such functionality, there are multiple ways in Angular. In this blog, we will discuss ng-template, which is the simplest of all.
 
Solution
 
Create an angular project by following the steps demonstrated here in the Angular documentation.
 
Create a model class tableOfContents.ts for the above recursive structure:
  1. export class TableOfContents {  
  2.    title: string;   
  3.    index: string;  
  4.    children: TableOfContents[];  
  5. }  

For the above model class, there can be 0 or more child elements for every list item.

Let's create a list of table of contents in app.component.ts and add some data:
  1. export class AppComponent {  
  2.    tableOfContents: TableOfContents[] = [  
  3.       { index: '1.' , title: 'Topic1' , children: [  
  4.          { index: '1.1.', title: 'Topic1.1', children: [] },  
  5.          { index: '1.2.', title: 'Topic1.2', children: [] }, ],   
  6.       },   
  7.       { index: '2.' , title: 'Topic2', children: [  
  8.          { index: '2.1.', title: 'Topic2.1', children: [] },  
  9.          { index: '2.2.', title: 'Topic2.2', children: [  
  10.             { index: '2.2.1.', title: 'Topic2.2.1', children: [] },  
  11.             { index: '2.2.2.', title: 'Topic2.2.2', children: [] },  
  12.          ],},  
  13.        ], },  
  14.     ]; } ];  
  15. }   
The above list can be rendered on UI, using angular ng-template. It takes a list of tabl of contents, and then render the template itseld where it finds a list of children. Below is the code for app.component.html:
  1. <ul>  
  2.    <ng-container  
  3.    *ngTemplateOutlet="recursiveListTmpl; context:{ list: tableOfContents }"  
  4.    ></ng-container>  
  5. </ul>  
  6.   
  7. <ng-template #recursiveListTmpl let-list="list">  
  8.    <ul *ngFor="let item of list">  
  9.       {{item.index}} {{ item.title }}  
  10.       <li *ngIf="item.children.length > 0">  
  11.          <ng-container  
  12.             *ngTemplateOutlet="recursiveListTmpl; context:{ list: item.children }"  
  13.          ></ng-container>  
  14.       </li>  
  15.    </ul>  
  16. </ng-template>    
<ng-container> passes the list to ng-template with id "recursiveListTmpl". It loops through the whole list. When it triggers the children list with length greater than 0 (line 10), it renders the "recursiveListTmpl" again and pass the list of children. Above code will generate the below show output in browser window.
 
Recursive Templates In Angular
 
Thank you for reading the blog. The source code is attached. Let me know your feedback and suggestions in the comments sections. And yes, you can request other tutorials as well.
 
Good Luck :)