Angular 2 How to get Angular to detect changes made outside Angular?

心不动则不痛 提交于 2019-11-27 22:52:27

You can do this by exporting NgZone inside your Angular app. Usually, you should do all things inside Angular, but if you really want to execute your logic out of Angular, you need to get the right zone, as you have said.

This trick is abusing Angular's dependency injection and hooking the injected zone on window object, as this issue shows. Declaring a dependency on NgZone, and assigning it to window.zoneImpl for exporting.

//our root app component
import {Component, NgZone} from 'angular2/core'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>

    </div>
  `,
})
export class App {
  constructor(zone: NgZone) {
    this.name = 'Angular2'
    window.app = this
    window.zoneImpl = zone
  }
}

After Angular bootstrapping, you should have a zoneImpl global variable. You can use the run method to kick Angular off.

zoneImpl.run(() => window.app.name = "new name!")

Live demo.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!