# How to run some code outside Angular

## 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 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);

}

}

In the above code snippet, you can see I have added one increment method in the component class, which will trigger on 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

Now let’s modify the code a little bit. Wrap the setInterval code inside runOutsideAngular which is instance method of NgZone. When the counter reaches 100, I am updating 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);
})
}

}



Reactions

Close Menu