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

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

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

Improving Angular performance by limiting change detection checks for components

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
Angular offers a hidden gem: ChangeDetectionStrategy.OnPush. This strategy allows Angular to skip change detection for components unless specific conditions are met, drastically improving app performance. However, it’s underutilized, even though it can work wonders in dynamic UIs.

? How Does ChangeDetectionStrategy.OnPush Work?

In Angular, the default change detection strategy (ChangeDetectionStrategy.Default) checks all components in the tree for changes — even if nothing has changed! This is fine for small apps, but for large apps, it kills performance.

With OnPush, Angular will only check a component if:

  1. Input properties change.
  2. Events (like clicks or user input) trigger updates.
  3. Observable subscriptions change.

✅ Example:


@Component({
selector: 'app-item',
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<p>{{ item.name }}</p>`
})
export class ItemComponent {
@Input() item!: { name: string };
}

? What’s Happening?

Angular will only check this component when one of the above triggers occurs, making it more performant.

This prevents Angular from checking components unnecessarily.

? Why You Should Use It


  • Boosts Performance: It reduces the amount of work Angular has to do, especially in complex or large apps.


  • Improved Control: You can precisely control when Angular should check your component for changes.


  • Low CPU Usage: Great for reducing CPU cycles when you have lots of components or a dynamic UI.


  • Works Best with Immutable Data: If you're using an immutable data model (e.g., NgRx, Redux), Angular can detect changes quickly when references change.

? How to Use It Effectively

To get the most out of OnPush, use immutable data structures. Angular relies on reference checks, so if the reference to an object doesn't change, it won’t trigger a re-render.

If you're doing manual data updates outside Angular's knowledge (like through setTimeout or WebSocket updates), use ChangeDetectorRef.detectChanges() to manually trigger change detection.

? Bonus: Mix OnPush with Default

You can even combine both strategies in the same app to optimize performance:


@Component({
selector: 'app-list',
template: `
<app-item *ngFor="let item of items" [item]="item"></app-item>
`,
changeDetection: ChangeDetectionStrategy.Default
})
export class ListComponent {
items = [{ name: 'Apple' }, { name: 'Banana' }];
}

In this case, ListComponent uses the default change detection strategy, but each ItemComponent uses OnPush to optimize performance further.

? Summary


  • ChangeDetectionStrategy.OnPush is one of the best-kept secrets for improving Angular app performance.


  • It limits unnecessary checks, making your app faster and more efficient.


  • It works well when you use immutable data patterns and can be easily mixed with other strategies.

Use it to make your Angular apps blazing fast!


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

 
Вверх Снизу