Angular. Change detection

Home » Tutorials » JavaScript » Angular. Change detection
Angular app is components tree. When something has changed in component (DOM changes, run timeout, intervals, promises, http requests), Angular checks all components for changes. It can affect negatively to app performance. In this video we’ll consider change detection strategy.
To prevent unnecessary checks, it need to set change detection strategy  property on @Component decorator with OnPush value.

Code lesson (change detection strategy OnPus)

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
Angular sets ChangeDetectionStrategy.Default for components by default.

Also developer can manage starting or shutting down change detection. For this purpose Angular core has the special class ChangeDetectorRef with several methods to control start/stop change detection.

Code lesson (user.component)

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

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserComponent {

  date = new Date();

  constructor(private _changeDetector: ChangeDetectorRef) {
    setInterval(() => {
      this.date = new Date();
      this._changeDetector.detectChanges();
    },1000);
  }

  changeTitle() {

  }

}

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *


The reCAPTCHA verification period has expired. Please reload the page.

Pin It on Pinterest

Share This