DEV Community

loading...
Cover image for Angular Change Detection-Detaching the Change Detector
This is Angular

Angular Change Detection-Detaching the Change Detector

Nikhil Dhawan
・2 min read

Hi all, in this series we are discussing Angular Change Detection, in the last post we discussed the OnPush change detection strategy, in this, we will see how can we customize the change detection using attaching and detaching change detector.

Detaching the Change Detector

So the concept here is like when in the component we detach the change detector, Angular will not perform change detection for that component and its subtree, and when we reattach it change detection will happen.
So let us see this with an example, full example can be referred from GitHub and Stackblitz.
Here we have 2 components parent and child, and we detach the child comp from the change detection, and based upon some condition we will attach it.
For this, we will need to inject ChangeDetectorRef in the constructor to be able to make use of this approach.

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.scss']
})
export class ChildComponent implements OnInit {

  constructor(private cdr:ChangeDetectorRef) { }

  ngOnInit(): void {
    this.cdr.detach();
  }
}
Enter fullscreen mode Exit fullscreen mode


`

The parent component has a data variable which we are showing in that component and also passing it to the child component as Input, and the data is displayed on HTML template other than this we have a button in the parent component to increment the value of data and two buttons in the child component one to detach and other to reattach the change detection, the setup will be as below screenshot
image
Now if you click on the increase value button you will see value is changing in both components, now click on Detach button and try to increase the value by the button which will cause the value in the parent component to change but not in the child component.
To get the latest value you can click on Reattach button then the angular will perform the change detection and you will see the latest value in both the components.
To experiment with the example you can try in below StackBlitz terminal.
Hope you were able to understand how we can take charge of change detection with help of ChangeDetectorRef.
If you liked it please share it with your friends or if any suggestions reach me out on Twitter or comment below.
Till next time Happy Learning!

Discussion (0)