Could you provide some particular examples of using ngZone?

Technology CommunityCategory: AngularCould you provide some particular examples of using ngZone?
VietMX Staff asked 3 years ago

There would be a lot of cases when you want to use NgZone, I can name two : 1. When you want something to run outside of Angular’s change detection. Lets say we want to do some calculation when user is scrolling and don’t want you to run change detection, in this case, you’d use NgZone:

constructor(private zone:NgZone){
   this.zone.runOutsideOfAngular(()=>{
      window.onscroll = ()=>{
       // do some heavy calculation : 
      }
    })
  }
  1. The exact opposite of above, where you have a function that is somehow outside of Angular’s zone and you want it to be inside, like when a third party library is doing some stuff for you and you want it to be bound to your Angular cycle.
this.zone.run(()=>{
    $.get('someUrl').then(()=>{
        this.myViewVariable = "updated";
    })
});