Communicate Between Components Using Dependency Injection

Part 3a of Advanced Angular Component Patterns

Isaac Mann
Angular In Depth
2 min readJan 5, 2018

--

Photo by Samuel Zeller on Unsplash

AngularInDepth is moving away from Medium. More recent articles are hosted on the new platform inDepth.dev. Thanks for being part of indepth movement!

02 Write Compound Components
03b Enhance Components with Directives

There is another problem we’ve found with our <toggle> component. We can’t have more than one <toggle-on> or <toggle-button> component in the same <toggle> and a <toggle-on> that is inside of another custom component won’t be picked up by the @ContentChild decorator.

Goals:

  1. Allow more than one child component of the same type
  2. Allow child components to be placed within the views of other custom components

Implementation:

We could solve (1) just by changing @ContentChild to @ContentChildren, but that can’t help us with (2). So we’ll use Angular’s dependency injection mechanism to solve both goals at the same time. You can inject any ancestor of a component into your component’s constructor and directly reference the ancestor component’s methods/members. Now any <toggle-on>, <toggle-off>, or <toggle-button> components will look for the closest <toggle> parent and use that toggle state.

Note: I initially planned to have this step use a service to share state between all the interested components, which would be a more conventional Angular way of doing things, but we can solve these issues without introducing services. I’ll address using services in part 12 of the series where it more directly correlates with the React Context Provider.

Outcome:

Now you can see in app.component.html that there are two <toggle-off> components that render as expected. There’s also an <other-component> that has its own <toggle-on> and <toggle-off> listening to changes from the same parent <toggle>.

--

--