• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

? Angular Challenge #1: Understanding OnPush Change Detection in Angular

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Welcome to the Angular Daily Challenge Series, where we decode real-world Angular concepts through fun and practical coding puzzles. This article dives into a common interview-level topic: OnPush change detection in Angular.

Let's analyze today's challenge and uncover the behavior of ChangeDetectorRef and OnPush.

❓ Angular OnPush Change Detection Challenge


Here's the scenario:


@Component({
selector: 'app-child',
template: `
<h1>Child Component</h1>
<span>{{ data().text }}</span>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ChildComponent {
data = input.required<{ text: string }>();
}

@Component({
template: `
<h1>Parent Component</h1>
<app-child [data]="data" />
`,
})
export class ChangeDetectionComponent {
#cdRef = inject(ChangeDetectorRef);
data = { text: 'Hello from Parent!' };

constructor() {
setTimeout(() => {
this.data.text = 'Updated from Parent!';
// Ensure the change is visible in the OnPush child
this.#cdRef.detectChanges();
}, 3_000);
}
}
✅ What Will Be Displayed in the Child After 3 Seconds?


✅ Output: "Updated from Parent!"

But why does this happen? Let's break it down with a deeper look into Angular's change detection system.

? How Angular OnPush Works


When you use ChangeDetectionStrategy.OnPush, Angular skips checking the component’s template unless one of these occurs:

  • The component receives a new reference via input signal
  • An event happens inside the component
  • Change detection is manually triggered using ChangeDetectorRef
? Why Mutation Doesn’t Trigger OnPush Detection


In our example, we changed:


this.data.text = 'Updated from Parent!';

This modifies a property of the object but doesn't change the object reference, so Angular doesn't detect this change on its own.

Hence, Angular won't rerender the child unless we force it using:


this.#cdRef.detectChanges();

This is how we manually notify Angular to run change detection for all components, including OnPush ones.

? Bonus Tip: 3_000 vs 3000 in JavaScript


You might have spotted:


setTimeout(() => { ... }, 3_000);

This is JavaScript numeric separator syntax introduced in ES2021. It’s functionally identical to 3000, but more readable.

✅ Benefits:

  • Easier to read large numbers (1_000_000, 3_000)
  • Especially useful for time intervals, byte sizes, and money values

✅ Use it in modern Angular projects, it improves code clarity without affecting performance.

? Learnings Recap

ConceptDescription
ChangeDetectionStrategy.OnPushOptimizes performance by skipping change detection unless needed
ChangeDetectorRef.detectChanges()Manually triggers Angular’s change detection
Mutating object propertiesDoesn’t trigger OnPush if the reference is unchanged
3_000 in setTimeout JavaScript numeric separator for better readability
? Challenge for You: Can You Optimize This?


In this challenge, we manually triggered change detection. But is that always the best approach?

? Explore These Alternatives:

  • ✅ Use immutable patterns: Replace the object entirely using this.data = { text: 'Updated' }
  • ⚡ Adopt Angular Signals (Angular 17+): Better reactivity with built-in efficiency
  • ? Try markForCheck() instead of detectChanges() in some cases

? What’s your go-to strategy for handling OnPush changes? Drop your ideas and code snippets in the comments!

? Stay Connected


??‍? Follow

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

for daily Angular challenges, JavaScript insights, and performance tips!


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу