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}
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.
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";1314 get filteredTodos() {} // return filtered todos15}
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.
1@Component({2 selector: "todo-list",3 template: `4 <todo-item5 *ngFor="let todo of todos"6 [todo]="todo"7 ></todo-item>8 `9})10export class TodoList {11 @Input() todos;12}1314@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.
1/**2 * The toggle event is handled here3 */4@Component({5 template: `6 <todo-filter [(filter)]="filter"></todo-filter>7 <todo-list8 [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";2021 get filteredTodos() {} // return filtered todos2223 toggleTodo(id: number) {} // handle toggle24}2526/**27 * TodoList has to pass the event on28 */29@Component({30 selector: "todo-list",31 template: `32 <todo-item33 *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}4344/**45 * TodoItem has to pass the event on46 */47@Component({48 selector: "todo-item",49 template: `50 <toggle-todo51 [todo]="todo"52 (toggle)="toggle.emit($event)"53 ></toggle-todo>5455 <span>56 {{ todo.title }}57 </span>58 `59})60export class TodoItem {61 @Input() todo;62 @Output() toggle = new EventEmitter<number>();63}6465/**66 * The event starts here67 */68@Component({69 selector: "toggle-todo",70 template: `71 <input72 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.
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 now 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.
1/**2 * Create the state service3 */4export class TodoState {5 todos = [6 { id: 0, title: "Buy milk", done: true },7 { id: 1, title: "Pay bills", done: false }8 ];910 get filteredTodos() {} // return filtered todos1112 toggleTodo(id: number) {} // handle toggle13}1415/**16 * Provide the TodoState in the Todos component17 */18@Component({19 template: `20 <todo-filter21 [(filter)]="todoState.filter"22 ></todo-filter>23 <todo-list24 [todos]="todoState.filteredTodos"25 ></todo-list>26 `,27 providers: [TodoState] // <--- provide it here28})29export class Todos {30 constructor(public todoState: TodoState) {}31}3233/**34 * Use the TodoState in the ToggleTodo component35 */36@Component({37 selector: "toggle-todo",38 template: `39 <input40 type="checkbox"41 [checked]="todo.done"42 (change)="todoState.toggleTodo(todo.id)"43 />44 `45})46export class ToggleTodo {47 @Input() todo;4849 /**50 * Inject the TodoState here51 */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";67 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