简体   繁体   中英

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

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>

I need to pass data through SidebarComponent to transfer it to 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.

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.

I'd say input binding is the way to go in most cases.

  1. It is the standard way of patent child communication. It will be what's expected by future developers to see, making debugging easier.
  2. Event passing data is to be avoided in general. If you are not using event binding with emitter for child to parent communication, you are out of the angular cycle and can cause unexpected problems.
  3. Using a service is always an option. Bear in mind though that services are singletons. Thus have their own limitations.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM