current position:Home>Change detection strategy of angular component

Change detection strategy of angular component

2022-05-15 02:12:54Maple moving forward

attribute :changeDetection   

Change detection strategy for the current component

  selector: 'app-xxx',
  templateUrl: 'XXX',
  styleUrls: ['XXX'],

When the component is instantiated ,Angular A change detector will be created , It is responsible for propagating the changes of each binding value of the component . The policy has the following values :


The default policy , Perform a dirty check , As long as the value changes , Conduct comprehensive change detection from parent component to child component . The test is comprehensive , But when there are many components , Low detection efficiency .


When entering data @Input When the reference of changes or an event triggers , Change detection is only carried out for components . Incomplete testing , But the detection efficiency is high .

Use ChangeDetectionStrategy.OnPush strategy , How to actively trigger change detection ?


It is Angular The basic classes of various views , Provide change detection function . The change detection tree collects all the views to be checked . Use these methods to add or remove views from the tree 、 Initialize change detection and explicitly mark these views as dirty , It means they have changed 、 Need to re render .

It has five ways :

markForCheck():  When view is used OnPush When changing the detection strategy , Explicitly mark the view as changed , So that it can detect changes again .

detach():   Separate the view from the change detection tree . Detached views are not checked until they are reattached . And detectChanges() Use a combination of , Local change detection can be realized .

detectChanges():   Check the view and its child views . And detach Combined use can realize local change detection .

checkNoChanges():   Check the change detector and its sub detectors , If any changes are detected , Throw an exception .

reattach():   Reattach the previously separated views to the change detection tree . The view will be attached to the tree by default .

Use : 

import { ChangeDetectionStrategy,ChangeDetectorRef } from '@angular/core';

    selector: 'xxx',
    exportAs: 'xxx',
    changeDetection: ChangeDetectionStrategy.OnPush

    private: cdr:ChangeDetectorRef

    this.cdr.markForCheck(); // Call... When needed 

Detailed principle :





copyright notice
author[Maple moving forward],Please bring the original link to reprint, thank you.

Random recommended