How to expose angular 2 methods publicly?

前端 未结 5 1374
再見小時候
再見小時候 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 09:59

    This is how i did it. My component is given below. Don't forget to import NgZone. It is the most important part here. It's NgZone that lets angular understand outside external context. Running functions via zone allows you to reenter Angular zone from a task that was executed outside of the Angular zone. We need it here since we are dealing with an outside call that's not in angular zone.

     import { Component, Input , NgZone } from '@angular/core';
     import { Router } from '@angular/router';
    
        @Component({
            selector: 'example',
            templateUrl: './example.html',
        })
        export class ExampleComponent {
                public constructor(private zone: NgZone, private router: Router) {
    
    //exposing component to the outside here
    //componentFn called from outside and it in return calls callExampleFunction()
            window['angularComponentReference'] = {
                zone: this.zone,
                componentFn: (value) => this.callExampleFunction(value),
                component: this,
            };
        }
    
        public callExampleFunction(value: any): any {
            console.log('this works perfect');
            }
        }
    

    now lets call this from outside.in my case i wanted to reach here through the script tags of my index.html.my index.html is given below.

    
    

    if you just type the below in developer console and hit enter it will invoke the exposed method and 'this works perfect ' will be printed on console.

     window.angularComponentReference.zone.run(() =>
    {window.angularComponentReference.componentFn(1);});
    

    entitlement is just some value that is passed here as a parameter.

提交回复
热议问题