26

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 ?

Tobias Gassmann
  • 11,399
  • 15
  • 58
  • 92

3 Answers3

53

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
}
Hari Das
  • 10,145
  • 7
  • 62
  • 59
18

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());
  }
}
alexpods
  • 47,475
  • 10
  • 100
  • 94
  • thanks! As it seems I was outside of the angular-zone (inside a click-callback of a google-map). Calling the lc.tick() did the trick :-) – Tobias Gassmann Oct 16 '15 at 16:47
  • 3
    Hmm, maybe [`NgZone:run`](https://github.com/angular/angular/blob/2.0.0-alpha.44/modules/angular2/src/core/zone/ng_zone.ts#L212) is more appropriate for your use case. It executes callback inside angular zone, after execution it runs LifeCycle.tick(). – alexpods Oct 16 '15 at 16:49
  • I agrre with @alexpods. There's another question that solves it that way, with `NgZone:run` (http://stackoverflow.com/questions/31352397/how-to-update-view-after-change-in-angular2-after-google-event-listener-fired) – EuAndreh Nov 24 '15 at 13:52
  • 1
    Another method is using `ChangeDetectorRef` like this: `this.chRef.detectChanges()`. – Post Impatica Sep 22 '16 at 04:56
  • 5
    LifeCycle doesnt exist anymore :/ – phil294 Mar 29 '17 at 13:20
2
setTimeout(function(){
//whatever u want here
},0)

ref : http://blog.mgechev.com/2015/04/06/angular2-first-impressions/

Aishwat Singh
  • 4,331
  • 2
  • 26
  • 48