Angular — Four Approaches to Implement Interdependent Components

Liu Ting Chun
4 min readSep 11, 2020

Component is the basic building block of Angular applications. A typical Angular application is consisted of many separated components. Normally, each component usually represents one particular feature. Yet, there are some complicated features that need to use multiple components to implement, for example, DropDownComponent and DropDownGroupComponent:

<drop-down-group>
<drop-down>...</drop-down>
<drop-down>...</drop-down>
<drop-down>...</drop-down>
</drop-down-group>

Data sharing is the most difficult part to solve when implementing this kind of interdependent components. Here I have summarized four common built-in approaches to tackle the communication problem.

Image from Deiser Blog

1. Component Injection

The simplest approach to establish a direct communication channel is through component injection from the children.

@Component(...)
export class DropDownComponent {
constructor(
parent: DropDownGroupComponent
) {
...
}
...
}

Component injection is a very useful feature powered by the Angular dependency injection engine which allows developers to inject the reference of any ancestor in the constructor through the engine. This approach is potentially the cleanest way to implement interdependent components with the least amount of code. Yet, the weakness is the strong coupling between two components, which leads to very bad code reusability. Hence, it is not suitable for complicated features. Besides, there is a limitation that the communication is totally bottom-up and child-driven, which makes it difficult to implement features that have parent-driven logic.

For a more detailed example, please check out the following article:

2. Service

The another approach that also utilizes the Angular dependency injection engine is service. It is basically an improved version of component injection. The concept is very similar. Yet, instead of…

Liu Ting Chun

Web developer from Hong Kong. Most interested in Angular and Vue. Currently working on a Nuxt.js + NestJS project.

Recommended from Medium

Lists

See more recommendations