0
0
Angularframework~5 mins

Zone.js and automatic detection in Angular

Choose your learning style9 modes available
Introduction

Zone.js helps Angular know when to update the screen automatically. It watches for changes in your app without you needing to tell it.

When you want Angular to refresh the view after a user clicks a button.
When your app gets data from the internet and you want the screen to update automatically.
When you use timers like setTimeout and want Angular to detect changes after they run.
When you want to avoid manually telling Angular to check for updates.
Syntax
Angular
Zone.current.run(() => {
  // your code here
});
Zone.js patches async operations like events, timers, and promises to detect changes.
Angular uses Zone.js internally, so you usually don't need to call it directly.
Examples
Zone.js detects this timer and tells Angular to update the view after 1 second.
Angular
setTimeout(() => {
  console.log('Timer done');
}, 1000);
This runs code inside the current zone, so Angular knows to check for changes after it finishes.
Angular
Zone.current.run(() => {
  console.log('Run inside zone');
});
Sample Program

This Angular component shows a counter and a button. When you click the button, a timer runs for 1 second. Zone.js detects the timer and automatically updates the counter on the screen without extra code.

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

@Component({
  selector: 'app-root',
  template: `
    <h1>Counter: {{ counter }}</h1>
    <button (click)="startTimer()">Start Timer</button>
  `
})
export class AppComponent {
  counter = 0;

  startTimer() {
    setTimeout(() => {
      this.counter++;
    }, 1000);
  }
}
OutputSuccess
Important Notes

You usually don't need to interact with Zone.js directly in Angular apps.

If you run code outside Angular's zone, the view won't update automatically.

You can use NgZone service to run code inside or outside the Angular zone if needed.

Summary

Zone.js helps Angular know when to update the screen automatically.

It watches async tasks like timers and events without extra code.

This makes your app update smoothly and easily.