Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular *ngFor recursive list tree template
<h1>Angular 2 Recursive List</h1>
<ul>
<ng-template #recursiveList let-list>
<li *ngFor="let item of list">
{{item.title}}
<ul *ngIf="item.children.length > 0">
<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.children }"></ng-container>
</ul>
</li>
</ng-template>
<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: list }"></ng-container>
</ul>
import { Component } from '@angular/core';
@Component({
selector: 'yourapp-any',
templateUrl: './any.component.html' // the magic's in here
})
export class AnyComponent {
constructor() { }
// its just list data from here down
public list = [
{
title: 'childless',
children: []
},
{
title: 'great grandparent',
children: [
{
title: 'childless grandsibiling',
children: []
},
{
title: 'grandparent',
children: [
{
title: 'childless sibiling',
children: []
},
{
title: 'another childless sibiling',
children: []
},
{
title: 'parent',
children: [
{
title: 'child',
children: []
},
{
title: 'another child',
children: []
},
]
},
{
title: 'another parent',
children: [
{
title: 'child',
children: []
},
]
},
]
},
{
title: 'another grandparent',
children: [
{
title: 'parent',
children: [
{
title: 'child',
children: []
},
{
title: 'another child',
children: []
},
{
title: 'a third child',
children: []
},
{
title: 'teen mother',
children: [
{
title: 'accident',
children: []
},
]
},
]
},
]
},
]
},
];
}
@Gargamil

This comment has been minimized.

Copy link

Gargamil commented Jun 19, 2017

Awesome, thanks!

But stay in mind:
<li *ngFor="let item of list">
can NOT be changed to something like
<li *ngFor="let item of list.children">.

In the second case, only the first level elements will be shown. (Not deeper levels..)

@Gwoks

This comment has been minimized.

Copy link

Gwoks commented Apr 12, 2018

Thanks man!! works perfect...

@alexnoise79

This comment has been minimized.

Copy link

alexnoise79 commented Apr 24, 2018

Hi, i was working on a similar solution to manage a recursive menu, but i have some problems with routerLinkActive

did you try something similar?

@ramnithik

This comment has been minimized.

Copy link

ramnithik commented Aug 3, 2018

If i add new children in list for dynamic process...the recursive list is crash??

@edgargomx

This comment has been minimized.

Copy link

edgargomx commented Oct 26, 2018

great, thanks man!!, works perfect to trees list 👍

@gmullersoriba

This comment has been minimized.

Copy link

gmullersoriba commented Dec 10, 2018

Nice !

@sakthikanth

This comment has been minimized.

Copy link

sakthikanth commented Jan 29, 2019

Thanks...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.