How to run some code outside Angular

The most common use of this service is to optimize performance when starting a work consisting of one or more asynchronous tasks that don’t require UI updates or error handling to be handled by Angular. Such tasks can be kicked off via runOutsideAngular, and if needed, these tasks can reenter the Angular zone via the run.

Let’s create one example to understand the zone.

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


@Component({
  selector: 'app-root',
  template: `
  <label>Counter</label>
  <h3> {{counter }} </h3>
<button (click)="increment()">increment</button>
 `,
  styles: []
})
export class AppComponent {


  counter = 0;
  interval;

  constructor(private zone: NgZone) {

  }
  increment() {
    this.counter = 0;
      this.interval = setInterval(() => {
        this.counter = this.counter + 1;
      }, 100);

  }
  
}
$ads={1}

In the above code snippet, I have added one increment method in the component class, which will trigger at the click of a button. Once this function fires, with will update the counter variable every 100ms and will update the UI because this code is running inside angular zone Which trigger the change detection. See the below image for the result.

Zone

Now let’s modify the code a little bit. Wrap the setInterval code inside runOutsideAngular , which is an instance method of NgZone. When the counter reaches 100, I update the counter value inside zone.run. the method, which will trigger the change detection and update the UI.

increment() {
    this.counter = 0;
    
    this.zone.runOutsideAngular(()=>{
      this.interval = setInterval(() => {
        this.counter = this.counter + 1;
        if(this.counter===100){
          this.zone.run(()=>{
            this.counter=this.counter;
            console.log('Code Is Running Inside Angular Zone and will trigger the change detection');
          });
        }
      }, 100);
    })
  }
import { Component, ElementRef, OnInit, NgZone, EventEmitter } from '@angular/core';


@Component({
  selector: 'app-root',
  template: `
  <label>Job Status</label>
  <h3> {{counter }} </h3>
<button (click)="increment()">increment</button>
 `,
  styles: []
})
export class AppComponent {

 
  counter = 1;
  interval;

  constructor(private zone: NgZone) {

  }
  increment() {
    this.counter = 0;
    
    this.zone.runOutsideAngular(()=>{
      this.interval = setInterval(() => {
        this.counter = this.counter + 1;
        if(this.counter===100){
          this.zone.run(()=>{
            this.counter=this.counter;
            console.log('Code Is Running Inside Angular Zone and will trigger the change detection');
          });
        }
      }, 100);
    })
  }
  
}

Zone

Further Reading

إرسال تعليق

Please do not post any spam link in the comment box😊

أحدث أقدم

Blog ads

CodeGuru