angularmean-stackangular-dataangular-renderer

What is the best approach to render data in Angular?


I have multiple post data inside an array. I want to render each post. There are two approaches to render :

1: create a reusable component and call it multiple times inside *ngFor

 <div *ngFor="let post of posts">
     <render-post [post]="post"><render-post>
 </div>

2: create a component and pass the array inside the component

<div>
     <render-post [posts]="posts"></render-post>
</div>

Solution

  • The more you break into small pieces, the better.

    I would go with the first one all day. It makes echo to Single Responsibility Principle, each component must have a unique responsability and do it well. The RenderPostComponent must be the way to render one post, and it must do it well. You can still create another component, parent of the previous one, that can be RenderPostListComponent which will contain your *ngFor and will get the array in parameter.

    So your final solution is a mix of both solution.

    RenderPostListComponent template

    <div *ngFor="let post of posts">
      <render-post [post]="post"><render-post>
    </div>
    

    Parent of the RenderPostListComponent template

    <div>
         <render-post-list [posts]="posts"></render-post-list>
    </div>