How to use Angular Component Recursively

Recursion
Nested Comments

Interface

First of all we will create an interface in models/Comment.ts

export default interface Comment {
text: string;
children?: Array<Comment>
}

Schema

Now we will create schema in data/comment-schema.ts

import Comment from "../models/Comment";export const CommentSchema: Comment[] = [
{
"text": "comment 1",
"children": [
{
"text": "comment 1.1",
"childeren": [
{
"text": "comment 1.1.1"
}
]
},
{
"text": "comment 1.2",
"childeren": [
{
"text": "comment 1.2.1"
},
{
"text": "comment 1.2.2"
}
]
}
]
},
{
"text": "comment 2",
"children": []
},
{
"text": "comment 3",
"children": []
}
];

Comment Component

Create a new comment component using given command

ng g c components/comment
@Input() comments: Array<Comment> | undefined;
@Component({
selector: 'app-comment',
styleUrls: ['./comment.component.scss'],
template: `
<div *ngFor="let comment of comments">
<ul>
<li>
{{comment.text}}
<app-comment [comments]="comment.children" *ngIf="comment.children"></app-comment>
</li>
</ul>
</div>
`
})
commentSchema: Array<Comment> = CommentSchema;
<app-comment [comments]="commentSchema"></app-comment>
Nested Comments

Read Next

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Piyush Jain

Piyush Jain

An avid front-end technologist with 9+ years of web industry experience. Self-motivated professional with broad technical skill-set and very strong attention.