Reputation: 1250
I have to generate a tree node with Angular. The object is called Page and each Page can have children and those children can also have their own children and so on.
Now I have to show the hierarchical structure in HTML from my Angular Page object.
Also, what I would want to indent the children like this:
You get the idea.
My page object is:
export class PageModel {
id!: number;
title?: string | undefined;
typeId?: string | undefined;
parentId?: number | undefined;
children?: PageModel[] | undefined;
publishedDateLocal?: string | undefined;
}
My html component is for now a simple table...
<table class="table">
<thead>
<tr>
<td>Title</td>
<td>Page Type</td>
<td>Published</td>
<td></td>
</tr>
</thead>
<tbody>
<tr *ngFor="let page of model.pageModels">
<td>{{ page?.title }}</td>
<td>{{ page?.pageTypeId }}</td>
<td>{{ page?.publishedDateLocal }}</td>
<td>
<a class="remove" (click)="deletePage(page.id)" [routerLink]="">
<span class="glyphicon glyphicon-trash text-danger"></span>
</a>
<a [routerLink]="['/pageAddEdit', page.id]">
Edit
</a>
</td>
</tr>
</tbody>
</table>
Thank you for any help
Upvotes: 0
Views: 3680
Reputation: 18271
I would recommend using a recursive structure for this.
Create a very simply component that takes PageModel
as an input. You can then display that, and look through each of the children using *ngFor
, like so:
@Component({
selector: 'hello',
template: `
<li>{{model.title}}</li>
<ul>
<hello *ngFor="let child of model.children" [model]="child"></hello>
</ul>
`,
styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
@Input() model: PageModel;
}
Here is a simple StackBlitz example
Upvotes: 1