Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Substitute for $scope.$apply?

Tags:

$scope.$apply will no longer be part of Angular 2. Then how do we let Angular know to update the DOM if any of the bound properties have been changed outside the regular angular execution context?

Taken from a blog post by Minko Gechev:

No more $scope.$apply

But how then AngularJS knows that anything outside it’s execution context has taken a place? Lets think where the changes might come from:

  • setTimeout
  • setInterval
  • prompt (yeah, there are people who still use it…)
  • XMLHttpRequest
  • WebSockets

For which the answer is:

enter image description here

I understand that patching the browser built-in javascript functions to notify of any changes to Angular is something that can be done in a relatively safe manner (without introducing subtle bugs) and would be very convenient for the developer. But what about third party APIs (such as jQuery.fadeIn) or if the browser exposes some new asynchronous API which isn't covered? What's the substitute for old $scope.$apply?

like image 518
Jaanus Varus Avatar asked Jun 09 '15 14:06

Jaanus Varus


People also ask

What is the replacement of the controller and scope in angular 2?

The controllers and $scope in Angular 1 have been replaced with “Components” in Angular 2. Hence we can say that it is a component-based framework, which uses zone.

Does angular 2 have scope?

Angular 2 is component based. Components combine concepts that we are already familiar with from AngularJS. The Angular 2 Component combines the AngularJS Directive, Controller, and Scope.

Is $scope still supported in Angular 2+?

In Angular 2, controllers and $scope were replaced by components and directives. Components are directives with a template.

What is alternative of rootScope in Angular?

What is alternative of rootScope in Angular? In similar way, you can use use the sharedService inside any component & fetch the returing output and used inside your view. That's it. I found this solution as a good alternative of rootScope.


1 Answers

  1. import NgZone from core
  2. private zone: NgZone in your constructor
  3. this.zone.run(() => {}); where you would normally scope.$apply

or

  1. ChangeDetectorRef
  2. private chRef: ChangeDetectorRef
  3. chRef.detectChanges();
like image 64
Post Impatica Avatar answered Oct 09 '22 19:10

Post Impatica