How to access a method from app.component from other component?

Angular2 has 2 ways to communicate between 2 components :

  1. Via @Input / @Output if the components have Parent-Child relationship
  2. Via a Service

Both ways are detailed in this article from Angular2 docs : https://angular.io/docs/ts/latest/cookbook/component-communication.html


I think the simplest way to achieve this is, basically create a static property in the app component that is populated when onInit

In app.component


export class AppComponent implements OnInit {
  static myapp;

 ngOnInit() {
    AppComponent.myapp = this;
 }
}

then in your component

import { AppComponent } from '../../app.component';
export class UsersComponent  implements OnInit {

 ngOnInit() {
    console.log(AppComponent.myapp);
 }
}

Assuming your class AppCompenent is saved as app.component.ts Then in your BuyTestComponent class, you need to first import it AppComponent like below

import {AppComponent} from '../app.component';

Assuming both files are saved in the same folder.

Instantiate it in your constructor like below

constructor(public myapp: AppComponent){}

then call it in your BuyTestComponent like below

this.myapp.testingFunction();

lastly, you need to register it as a provider in your app.module.ts

providers: [
 AppComponent,
]

If you need access to a function from several places, consider putting it in a service as @tibbus mentioned.

utility.service.ts

@Injectable()
export class UtilityService{

    TestingFunction(){}
}

Next, make sure the service is listed in the providers array of your main module:

app.module.ts

// https://angular.io/docs/ts/latest/guide/ngmodule.html#!#ngmodule-properties
@NgModule({ 
  imports:      [ BrowserModule],
  declarations: [ AppComponent, BuyTestComponent ],
  providers:    [ UtilityService ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

You can then inject that service in any component that needs access to the function

buy-test.component.ts

@Component(...)
export class BuyTestComponent {

    //inject service into the component
    constructor(private util:UtilityService){}

    TestHere() {
        //access service function
        this.util.TestingFunction();
    }
}