0
0
Angularframework~30 mins

When to use OnPush in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
When to use OnPush
📖 Scenario: You are building a simple Angular app that shows a list of tasks. Each task has a name and a status. You want to make the app faster by telling Angular when to update the task list component.
🎯 Goal: Learn how to use the OnPush change detection strategy in Angular to improve performance by updating the component only when its input data changes.
📋 What You'll Learn
Create a standalone Angular component called TaskListComponent that displays a list of tasks.
Add a configuration variable to set the change detection strategy to OnPush.
Use an @Input() property called tasks to receive the list of tasks.
Add a button in the parent component to update the tasks list immutably and see the effect of OnPush.
💡 Why This Matters
🌍 Real World
Using <code>OnPush</code> helps Angular apps run faster by reducing unnecessary updates. This is important in apps with many components or complex UI.
💼 Career
Understanding change detection strategies like <code>OnPush</code> is key for Angular developers to write efficient, scalable applications.
Progress0 / 4 steps
1
Create the TaskListComponent with tasks input
Create a standalone Angular component called TaskListComponent with an @Input() property named tasks of type string[]. The component template should display each task inside an unordered list <ul> with list items <li>.
Angular
Need a hint?

Use @Input() to receive data from the parent. Use *ngFor to loop over tasks in the template.

2
Set the change detection strategy to OnPush
Add the changeDetection property to the @Component decorator and set it to ChangeDetectionStrategy.OnPush. Import ChangeDetectionStrategy from @angular/core.
Angular
Need a hint?

Import ChangeDetectionStrategy and add changeDetection: ChangeDetectionStrategy.OnPush inside the @Component decorator.

3
Use the TaskListComponent in a parent component
Create a parent component called AppComponent that uses <app-task-list> in its template. Define a tasks array property with these exact values: ['Wash dishes', 'Do laundry', 'Buy groceries']. Pass this array to app-task-list using property binding [tasks].
Angular
Need a hint?

Use property binding [tasks] to pass the tasks array to the child component.

4
Add a button to update tasks immutably
In AppComponent template, add a button with text Complete first task. When clicked, update the tasks array by creating a new array that removes the first task. Use the spread operator to create the new array. This shows how OnPush detects changes only when the input reference changes.
Angular
Need a hint?

Use the spread operator and slice(1) to create a new array without the first task.