angular 2.0 equivalent to $scope.$apply

后端 未结 3 614
一向
一向 2020-12-29 05:22

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

相关标签:
3条回答
  • 2020-12-29 05:52

    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
    }
    
    0 讨论(0)
  • 2020-12-29 05:53

    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());
      }
    }
    
    0 讨论(0)
  • 2020-12-29 05:55
    setTimeout(function(){
    //whatever u want here
    },0)
    

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

    0 讨论(0)
提交回复
热议问题