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

前端 未结 1 1807
隐瞒了意图╮
隐瞒了意图╮ 2020-12-06 05:21

I am trying to create a simple example project to test the angular 2 change detection mechanism: I create a pure javascript object in script tags on the main index page. it

相关标签:
1条回答
  • 2020-12-06 05:33

    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.

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