How to expose angular 2 methods publicly?

前端 未结 5 1377
再見小時候
再見小時候 2020-11-28 09:40

I am currently working on porting a Backbone project to an Angular 2 project (obviously with a lot of changes), and one of the project requirements requires certain methods

5条回答
  •  清歌不尽
    2020-11-28 10:14

    Just make the component register itself in a global map and you can access it from there.

    Use either the constructor or ngOnInit() or any of the other lifecycle hooks to register the component and ngOnDestroy() to unregister it.

    When you call Angular methods from outside Angular, Angular doesn't recognize model change. This is what Angulars NgZone is for. To get a reference to Angular zone just inject it to the constructor

    constructor(zone:NgZone) {
    }
    

    You can either make zone itself available in a global object as well or just execute the code inside the component within the zone.

    For example

    calledFromOutside(newValue:String) {
      this.zone.run(() => {
        this.value = newValue;
      });
    }
    

    or use the global zone reference like

    zone.run(() => { component.calledFromOutside(newValue); });
    

    https://plnkr.co/edit/6gv2MbT4yzUhVUfv5u1b?p=preview

    In the browser console you have to switch from to plunkerPreviewTarget.... because Plunker executes the code in an iFrame. Then run

    window.angularComponentRef.zone.run(() => {window.angularComponentRef.component.callFromOutside('1');})
    

    or

    window.angularComponentRef.zone.run(() => {window.angularComponentRef.componentFn('2');})
    

提交回复
热议问题