Chris Kohler

Navigate back to the homepage

How to avoid Prop-drilling in Angular

Chris Kohler
August 2nd, 2020 · 4 min read

How to avoid Prop-drilling in Angular

How to avoid Prop-drilling in Angular, or how to apply the idea of React Context to Angular.

Table of Contents

  • Should I be interested?
  • The „how“ and the „where“
  • What is Prop Drilling?
  • The problem of Prop Drilling by example
  • How to avoid prop drilling
  • Global state vs. Context-like state vs. Prop drilling
  • Summary

Tldr;

If you prefer to use Input/Outputs in Angular you might find yourself writing a lot of boilerplate code to propagate events up the component hierarchy. As a solution you could add that state into a global service.

A better approach is to put the state into a service provided by a component on the highest level necessary. This can be achieved by using the hierarchical dependency injection system of Angular.

Should I be interested?

If you have all your state in a global store, this article is not for you. But..

  • if you try to keep your state and logic as close as possible to where it is used
  • and you often end up propagating state and actions through multiple components

..then read on 👇

The „how“ and the „where“

State management is a broad topic. To make it easier the topic can be divided into two parts. The “how” and the “where”.

The “how” defines how to handle state. Are you using redux, mobx, ngrx or just a simple class with getter and setter? Is your data immutable or not?

The “where” defines whether you have multiple stores / states. For example a common pattern with redux is to have one global store. But it’s possible to have local stores or feature stores. State can be within a single component or within a subtree of components.

In this blogpost I don’t cover the “how” but look into the “where”. I try to keep the examples as simple as possible. That’s why I don’t use any “fancy” state management library, only pure typescript and a mutable data structure.

What is Prop Drilling?

Kent C. Dodds wrote a good blog post about Prop Drilling.

Prop drilling is propagating or threading data through multiple levels of components. Since we don’t use props in Angular we could also call it input/output drilling.

The problem of Prop Drilling by example

Let’s look at the problem by writing a small todo app.

Disclaimer: The example is not complete. Some parts might be oversimplified or overengineered.

Simple List

We start with a simple “one-component” application with a list of todos.

1@Component({
2 selector: "todo-list",
3 template: `
4 <div *ngFor="let todo of todos">
5 {{ todo }}
6 </div>
7 `
8})
9export class TodoList {
10 todos = ["Buy milk", "Pay bills"];
11}

SimpleList

Add a Filter

Now we want to add a filter. Since we want to share our state we create a component called “Todos” which contains the state.

WithFilter

1@Component({
2 template: `
3 <todo-filter [(filter)]="filter"></todo-filter>
4 <todo-list [todos]="filteredTodos"></todo-list>
5 `
6})
7export class Todos {
8 todos = [
9 { title: "Buy milk", due: "today" },
10 { title: "Pay bills", due: "tomorrow" }
11 ];
12 filter = "today";
13
14 get filteredTodos() {} // return filtered todos
15}

Add a TodoItem Component

Now we want to replace the todo string in the TodoList component with a component. We create a “TodoItem” component for that.

WithTodoItem

1@Component({
2 selector: "todo-list",
3 template: `
4 <todo-item
5 *ngFor="let todo of todos"
6 [todo]="todo"
7 ></todo-item>
8 `
9})
10export class TodoList {
11 @Input() todos;
12}
13
14@Component({
15 selector: "todo-item",
16 template: `
17 <div>{{ todo.title }}</div>
18 `
19})
20export class TodoItem {
21 @Input() todo;
22}

Add a ToggleTodo Component

Now we want to add another component within “TodoItem” called “ToggleTodo”. This component should display a checkbox and call a method named “toggleTodo()” on the state.

Note: For such a simple application this ToggleTodo component definitely is too much component splitting. I do it here to make the problem of prop drilling more visible.

WithToggleItem

1/**
2 * The toggle event is handled here
3 */
4@Component({
5 template: `
6 <todo-filter [(filter)]="filter"></todo-filter>
7 <todo-list
8 [todos]="filteredTodos"
9 (toggle)="toggleTodo($event)"
10 >
11 </todo-list>
12 `
13})
14export class Todos {
15 todos = [
16 { title: "Buy milk", due: "today" },
17 { title: "Pay bills", due: "tomorrow" }
18 ];
19 filter = "today";
20
21 get filteredTodos() {} // return filtered todos
22
23 toggleTodo(id: number) {} // handle toggle
24}
25
26/**
27 * TodoList has to pass the event on
28 */
29@Component({
30 selector: "todo-list",
31 template: `
32 <todo-item
33 *ngFor="let todo of todos"
34 [todo]="todo"
35 (toggle)="toggle.emit($event)"
36 ></todo-item>
37 `
38})
39export class TodoList {
40 @Input() todos;
41 @Output() toggle = new EventEmitter<number>();
42}
43
44/**
45 * TodoItem has to pass the event on
46 */
47@Component({
48 selector: "todo-item",
49 template: `
50 <toggle-todo
51 [todo]="todo"
52 (toggle)="toggle.emit($event)"
53 ></toggle-todo>
54
55 <span>
56 {{ todo.title }}
57 </span>
58 `
59})
60export class TodoItem {
61 @Input() todo;
62 @Output() toggle = new EventEmitter<number>();
63}
64
65/**
66 * The event starts here
67 */
68@Component({
69 selector: "toggle-todo",
70 template: `
71 <input
72 type="checkbox"
73 [checked]="todo.done"
74 (change)="toggle.emit(todo.id)"
75 />
76 `
77})
78export class ToggleTodo {
79 @Input() todo;
80 @Output() toggle = new EventEmitter<number>();
81}

As you can see, this leads to a lot of boilerplate since we have to emit the toggle event from component to component.

PropDrilling

This is the problem of prop drilling. To set the state from the ToggleTodo we have to go through TodoItem and TodoList.

How to avoid prop drilling

React has a nice solution for that problem. It’s called context.

https://reactjs.org/docs/context.html

Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Angular doesn’t have a functionality like context but we can use its powerful dependency injection system to achieve the same goal.

Note that React’s context and Angular’s DI are fundamentally different in how the work.

Angular’s hierarchical dependency injection system

Angular comes with a hierarchical dependency injection system. I’ve created a infographic poster to visualise that system.

What you need to know for know is that every component has its own injector and that child components can access the services from further up in the hierachy.

Todo App with context-like state

So let’s use the power of Angular’s DI system to create a context for our state.

We are going to provide the state in the Todos component and inject it in the ToggleTodo component.

ProvideInject

1/**
2 * Create the state service
3 */
4export class TodoState {
5 todos = [
6 { id: 0, title: "Buy milk", done: true },
7 { id: 1, title: "Pay bills", done: false }
8 ];
9
10 get filteredTodos() {} // return filtered todos
11
12 toggleTodo(id: number) {} // handle toggle
13}
14
15/**
16 * Provide the TodoState in the Todos component
17 */
18@Component({
19 template: `
20 <todo-filter
21 [(filter)]="todoState.filter"
22 ></todo-filter>
23 <todo-list
24 [todos]="todoState.filteredTodos"
25 ></todo-list>
26 `,
27 providers: [TodoState] // <--- provide it here
28})
29export class Todos {
30 constructor(public todoState: TodoState) {}
31}
32
33/**
34 * Use the TodoState in the ToggleTodo component
35 */
36@Component({
37 selector: "toggle-todo",
38 template: `
39 <input
40 type="checkbox"
41 [checked]="todo.done"
42 (change)="todoState.toggleTodo(todo.id)"
43 />
44 `
45})
46export class ToggleTodo {
47 @Input() todo;
48
49 /**
50 * Inject the TodoState here
51 */
52 constructor(public todoState: TodoState) {}
53}

Introducing the TodoState service in this example reduced the boilerplate of propagating the toggle event from component to component. It’s a nice way to reduce boilerplate without the need to throw the state into the “global bucket”.

Global state vs. Context-like state vs. Prop drilling

I think there is a place for all concepts, even in the same application.

Personally I try to start with Inputs/Outputs. It is easier to follow and refactor (like a pure function) and change detection is also easier to understand.

When I feel that the added boilerplates negates the benefits of Inputs/Outputs I switch to context-like state services. This reduces boilerplate but still keeps the state as close as possible to where it is used.

Some state is global. One common example is the selected theme. In this case I’d use a global service like this one:

1@Injectable({
2 providedIn: "root"
3})
4export class ThemeProvider {
5 selectedTheme = "light";
6
7 selectLightTheme() {
8 this.selectedTheme = "light";
9 }
10 selectDarkTheme() {
11 this.selectedTheme = "dark";
12 }
13}

You might ask yourself why not make everything global. In small applications like the todo example from this post, putting the state into a global service is fine. But the more complex you application is, the more important it is to keep your logic and state as close as possible to where you use it.

Summary

In this blog post you learned that there is not just global or local state in Angular. With the power of the hierarchical DI system we can provide a state service in the the exact (highest) place in the component tree where we need it to be. This is often a nice compromise between having a local state and making it globally available.

If you liked the article 🙌, spread the word and follow me on Twitter for more posts on web technologies.

Did you find typos 🤓? Please help improve the blogpost and open an issue here

More articles from Chris Kohler

It’s a trap - The biggest pitfall of String.prototype.replace()

How to avoid the biggest pitfall of the replace function

June 30th, 2020 · 2 min read

Lessons learned from building a Grid List in React Native

How to build a robust grid list in React Native

June 5th, 2020 · 2 min read
© 2023 Chris Kohler
Link to $https://twitter.com/kohlerchristianLink to $https://github.com/christiankohlerLink to $https://instagram.com/mrchriskohlerLink to $https://www.linkedin.com/in/mr-christian-kohler/