0
0
Angularframework~30 mins

OnPush change detection strategy in Angular - Mini Project: Build & Apply

Choose your learning style9 modes available
Using OnPush Change Detection Strategy in Angular
📖 Scenario: You are building a simple Angular app that shows a list of tasks. You want to make the app faster by telling Angular to check for changes only when the task list changes explicitly.
🎯 Goal: Build an Angular component that uses the OnPush change detection strategy to update the task list only when new tasks are added.
📋 What You'll Learn
Create a component with a task list array
Add a variable to track the new task input
Use OnPush change detection strategy in the component decorator
Add a method to add new tasks and update the task list immutably
💡 Why This Matters
🌍 Real World
OnPush change detection helps Angular apps run faster by checking for changes only when data changes explicitly. This is useful in apps with many components or large data sets.
💼 Career
Understanding OnPush is important for Angular developers to write efficient, scalable applications and improve app performance.
Progress0 / 4 steps
1
Set up the initial task list
Create a component class called TaskListComponent with a public property tasks initialized to an array with these exact strings: 'Buy groceries', 'Walk the dog', 'Read a book'.
Angular
Need a hint?

Remember to create a public property named tasks and assign the exact array of strings.

2
Add a variable for new task input
Add a public string property called newTask initialized to an empty string '' inside the TaskListComponent class.
Angular
Need a hint?

Just add a new property newTask and set it to an empty string.

3
Set OnPush change detection strategy
Modify the @Component decorator to add changeDetection: ChangeDetectionStrategy.OnPush. Import ChangeDetectionStrategy from @angular/core.
Angular
Need a hint?

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

4
Add method to add new tasks immutably
Add a public method called addTask() inside TaskListComponent. It should add the string in newTask to the tasks array immutably (create a new array with the new task appended). Then reset newTask to an empty string ''.
Angular
Need a hint?

Use the spread operator to create a new array with the new task added. Then clear newTask.