Comparing markForCheck and detectChanges: What's the difference?


 In Angular, there is a difference between the markForCheck and detectChanges methods. Both are used for change detection, but they serve different purposes.

markForCheck 

The markForCheck method marks a component for check- ing even if it has already been checked. This is useful when an external event has changed something in the component and you want to make sure that the changes are detected.

The markForCheck function in angular is used to trigger a change detection cycle for a component. This function is typically used when there is an async event that occurs, and you need to make sure that the component is updated. 

For example, if you have a component that displays data from an API call, you would use the markForCheck function to make sure that the component is updated when the API call returns new data

How does NgZone help us withChange Detection?


NgZone is a service that Angular uses to keep track of changes that occur in the application. By default, when something changes in the application, NgZone will run a check to see if any other part of the application needs to be updated. If not, then nothing happens.

However, there are times when we need to explicitly tell NgZone that something has changed and that it should run a check. This is where markForCheck comes in. By calling markForCheck on an element or directive, we are telling NgZone that this element or directive has changed and it should be checked again.

This is useful when we make changes to data outside of Angular (for example, when using an API), as Angular will not know that the data has changed unless we tell it to.


private loadComponentData() {
    this.dataService
      .getUserProfileObservable()
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe((userProfile) =>
        this.ngZone.run(() => {
          this.userProfile = userProfile;
          this.cdr.markForCheck();
        })
      );
  }
}

detectChanges 

The detectChanges method does a full change detection check on a component, even if it doesn't think that anything has changed. This is useful for forcing Angular to check for changes that may have been caused by an asynchronous event.

 ChangeDetectorRef is an angular class that helps in detecting changes in the components. It is used for different purposes such as when the component needs to be checked for changes, when the component is destroyed, and when the template needs to be updated. The ChangeDetectorRef class provides a method called detectChanges() which checks if there has been a change in the data bindings of a component or not. If there is a change, then it updates the DOM accordingly. 


import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  aquaticCreatures = ['shark', 'dolphin', 'octopus'];

  addAquaticCreature(newAquaticCreature) {
    this.aquaticCreatures.push(newAquaticCreature);
  }
}


<input #inputAquaticCreature type="text" placeholder="Enter a new creature">
<button (click)="addAquaticCreature(inputAquaticCreature.value)">Add creature</button>

<app-child [data]="aquaticCreatures"></app-child>


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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent {
  @Input() data: string[];

  constructor(private cd: ChangeDetectorRef) {}

  refresh() {
    this.cd.detectChanges();
  }
}

There are several reasons why we should use ChangeDetectorRef detectChanges method in our Angular application. First of all, using ChangeDetectorRef helps improve performance because we are only checking for changes when we need to and not on every change detection cycle. Secondly, it allows us to fine-tune when we want to update the template.

When and why to use markForCheck and detectChanges

When working with Angular, there are two mechanisms that can be used to tell the framework that a component or directive needs to be checked for changes: markForCheck and detectChanges.

So, when should you use each one?

Generally speaking, you should use markForCheck when you need to programmatically tell Angular that a component or directive needs to be checked for changes. This is typically done when you're working with an external library that isn't aware of Angular's change detection mechanism.

On the other hand, detectChanges should be used when you need to manually trigger change detection in a component or directive. This might be necessary if you're doing something like dynamically adding/removing elements from the DOM.

Post a Comment

1 Comments