How to use Angular Component Recursively

Piyush Jain
3 min readApr 10, 2022

In this tutorial we will learn how to Recursively call Angular Component.

Example: Nested Comments, Nested Menu

Recursion

If you will go along with me final result will look like below.

Nested Comments

Without wasting any time let’s start.

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

Now in app.component.ts we will create a variable for comment schema.

Now we will add schema in comment component using Input Decorator.

@Input() comments: Array<Comment> | undefined;

Now we will render nested comments in template. Copy and paste below code in comment.component.html or in template property of Component decorator.

@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>
`
})

Now we will get comment schema in app.component.ts file

commentSchema: Array<Comment> = CommentSchema;

Now we will call app-component in app.component.html file.

<app-comment [comments]="commentSchema"></app-comment>

Thats it. If you will run your code it will look like below.

Nested Comments

If you liked this please give a clap.

Also let us know who you are doing this in your project. Do share if you know any other approach.

In Next Article we will enhance this so that user can reply and like comments.

Let me know if you have any doubts.

Source Code is available on github: https://github.com/piyush303/recursively-use-angular-component

You can play here with this example: https://codesandbox.io/s/recursively-use-angular-component-nr7y62

Read Next

--

--

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.