[英]What could be the best approach to pass data in nested child components, in Angular?
I have a scenario, where for example我有一个场景,例如
<parent-comp>
<side-bar></side-bar>
<item-details></item-details>
</parent-comp>
<side-bar>
<item-list></item-list>
</side-bar>
I need to share items list into the components 'ItemListComponent' and 'ItemDetailsComponent', keeping the hierarchy in mind我需要将项目列表共享到组件“ItemListComponent”和“ItemDetailsComponent”中,并牢记层次结构
Approach 1方法一
I can fetch the items from ItemService in ParentComponent and send it via attribute/property <sidebar [pages]="pages"></sidebar>
>>> <item-list [pages]="pages"></item-list>
and <item-details[pages]="pages"></item-details>
我可以从 ParentComponent 中的 ItemService 获取项目并通过属性/属性发送它<sidebar [pages]="pages"></sidebar>
>>> <item-list [pages]="pages"></item-list>
和<item-details[pages]="pages"></item-details>
I need to pass data through SidebarComponent to transfer it to ItemListComponent.我需要通过 SidebarComponent 传递数据以将其传输到 ItemListComponent。
Approach 2方法二
Fetching items from ItemService in the ParentComponent and instead of passing via attribute/property it emits the data (RxJs) let say with event name 'ItemDataFetched', and ItemList/ItemDetails component subscribed to that event.从 ParentComponent 中的 ItemService 获取项目,而不是通过属性/属性传递,它发出数据(RxJs),比如事件名称“ItemDataFetched”,以及订阅该事件的 ItemList/ItemDetails 组件。
What will be the best approach among the two?两者中最好的方法是什么? or is there any other better approach?或者还有其他更好的方法吗?
Check here: https://angular.io/guide/component-interaction the ways proposed by the angular team.在此处查看: https : //angular.io/guide/component-interaction angular 团队提出的方法。
I'd say input binding is the way to go in most cases.我会说输入绑定是大多数情况下的方法。
By the way, I would expect the child component to inform the parent of the selection and pass only the selected item's page to the item-details component.顺便说一句,我希望子组件通知父组件选择并仅将所选项目的页面传递给项目详细信息组件。 Not the entire collection.不是整个集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.