Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 2.0 equivalent to $scope.$apply

I am trying to get started with angular 2.0, now I was wondering how I can initiate an update to the view after some external event changed data.

In details I have a google map and a handler for a click-event on the map. After the user clicks on the map I store latitude and longitude of the click in to variables on the controller

this.lat = event.latLng.lat();
this.lon = event.latLng.lon();

In the view I want to display these values

<div> this is my spot: {{lat}} and {{lon}} </div>

In angular 1 I would simply wrap the assignment in the controller in a call to $scope.$apply().

What is the preferred way to go about updating views in angluar 2.0 ?

like image 271
Tobias Gassmann Avatar asked Sep 10 '25 16:09

Tobias Gassmann


2 Answers

Try to import ChangeDetectorRef from angular core as follow

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

in constructor

constructor(private chRef: ChangeDetectorRef){
  chRef.detectChanges(); //Whenever you need to force update view
}
like image 52
Hari Das Avatar answered Sep 12 '25 09:09

Hari Das


Mostly, you don't need to do anything to update the view. zone.js will do everything for you.

But if for some reason you want to fire change detection manually (for example if your code is running outside of an angular zone) you can use LifeCycle::tick() method to do it. See this plunker

import {Component, LifeCycle, NgZone} from 'angular2/angular2'

@Component({
  selector: 'my-app',
  template: `
    <div>
      Hello world!!! Time: {{ time }}.
    </div>
  `
})
export class App {
  time: number = 0;

  constructor(lc: LifeCycle, zone: NgZone) {
    zone.runOutsideAngular(() => {
      setInterval(() => {
        this.time = Date.now();

        lc.tick(); // comment this line and "time" will stop updating
      }, 1000);
    })
  }
  doCheck() {
    console.log('check', Date.now());
  }
}
like image 40
alexpods Avatar answered Sep 12 '25 08:09

alexpods