简体   繁体   English

在 Angular 中呈现数据的最佳方法是什么?

[英]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 1:创建一个可复用的组件并在*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 2:创建一个组件并在组件内部传递数组

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

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. RenderPostComponent 必须是渲染一篇文章的方式,而且它必须做得很好。 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.您仍然可以创建另一个组件,即前一个组件的父组件,它可以是 RenderPostListComponent,它将包含您的*ngFor并在参数中获取数组。

So your final solution is a mix of both solution.所以你的最终解决方案是两种解决方案的混合。

RenderPostListComponent template RenderPostListComponent 模板

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

Parent of the RenderPostListComponent template RenderPostListComponent 模板的父级

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular - 检索数据的最佳方法是什么 - Angular - what is the best approach in retrieving data Angular 7-什么是守卫的最佳方法 - Angular 7 - what is the best approach for guards 从角度2开始,什么是最佳方法? - Starting with angular 2, what is the best approach? 在 Angular 的嵌套子组件中传递数据的最佳方法是什么? - What could be the best approach to pass data in nested child components, in Angular? Angular 的数据库抽象层的最佳方法是什么? - What is the best approach to database abstraction layer for Angular? 通过 http 将大量数据从 Angular 发送到 Express 的最佳方法是什么? - What is the best approach to send huge chunks of data from Angular to Express via http? 根据 Angular 8 中的某些条件隐藏/显示组件的最佳方法是什么 - What is the best approach to hide/show component depending on some condition in Angular 8 Angular - 可能需要跟进 http 调用,最好的方法是什么? - Angular - Possible follow up http call needed, what is best approach? Angular 2+计时器要应用相同,最好的方法是什么? - Angular 2+ timer for to app the same, what would be the best approach? in Angular 13、如何通过依赖解析调用内部子组件到父组件? 刷新网格数据的最佳方法是什么? - in Angular 13, How can i call inner child component to parent component with dependency resolve ? what is the best approach to refresh grid data?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM