0

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>
Axiome
  • 695
  • 5
  • 18
sanjay
  • 514
  • 2
  • 5
  • 14
  • According to Smart. - Dumb Component principal it should be 1st approach That rules. Let imagine you want to reuse the render-post component somewhere !!! – Talk is Cheap Show me Code Feb 28 '20 at 05:10
  • to reuse the render-post component somewhere, posts can also be pass the same as 2nd approach. – sanjay Feb 28 '20 at 05:17
  • It comes down to how complex your 2 components will be. Yeah, 2 components, potentially. One is post list, and the other is individual post. So your question is not really valid because you are talking about 2 components in essence, and . If your is complex which contains other children components apart from , you might define a specific component for it, which is method 1. – Carter Feb 28 '20 at 05:36

1 Answers1

0

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>
Axiome
  • 695
  • 5
  • 18