Angular Recursive component

Original author: Netanel Basal
  • Transfer

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

In this short article, we will create a component that will use an array of comments with several levels of nesting as an input parameter 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, make them static.

Comments component


@Component({
  selector: 'comments',
  template: `
     
  • {{comment.text}}
`, }) export class CommentComponent { @Input() comments; }

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

App component


@Component({
  selector: 'my-app',
  template: `
   
  `,
})
export class App {
  postComments = postComments;
}

Result



References


stackblitz angular ru telegram example

Also popular now: