📜 ⬆️ ⬇️

Angular. Recursive component


There are situations when you need to display a tree with an indefinite amount of nested data of the same type and it is desirable not to duplicate the code at each level.

In this short article, we will create a component that will use as an input parameter an array of comments with several nesting levels and display them recursively .

Data structure


const comments:Comment[] = [ { text: "1", comments: [ { text: "1.1", comments: [ { text: "1.1.1 " } ] }, { text: "1.2", comments: [ { text: "1.2.1" } ] } ] }, { text: "2", comments: [ { text: "2.1", comments: [ { text: "2.1.1" } ] } ] } ]; 

This is the data we expect to receive from the server. For the current example, let's make them static.

Comments component


 @Component({ selector: 'comments', template: ` <div *ngFor="let comment of comments"> <ul> <li> {{comment.text}} <comments [comments]="comment.comments" *ngIf="comment.comments"></comments> </li> </ul> </div> `, }) export class CommentComponent { @Input() comments; } 

As you can see, we call the component recursively . In the case when there are no nested comments, the ngif directive is used to not display the component.
')

App Component


 @Component({ selector: 'my-app', template: ` <comments [comments]="postComments"></comments> `, }) export class App { postComments = postComments; } 

Result



Links


stackblitz example
angular ru telegram

Source: https://habr.com/ru/post/351750/


All Articles