How can I setup a global function that can be accessed throughout all views?
In app.component.ts I added a simple method
openShare() {console.log("button clicked")}
and then in my nav I have
<button ion-button right (click)="openShare()">
<ion-icon name="md-share"></ion-icon>
</button>
When I try to access this from any page I get the following.
self.context.openShare is not a function
It does however execute fine if I put it directly in the constructor (e.g this.openShare(); ), but when calling from any page using a (click) function it just doesn't work.
Is app.component.ts not global? I thought this is where I would place it, but maybe I am missing something.
Basically its a function for a simple button on the nav, I need it to be global though since its used on every page.
Any help would be appreciated, still figuring Ionic 2 out.
You can easily do that using
Providers
.When you need to use that functionality (or provider), you just need toinject
it into your related component.That is it.Method 1:
You can create a Provider using CLI.
your-provider.ts
app.module.ts
your-view.ts
Method 2: Creat an
abstract
base class.my-base-class.ts
my-view.ts
Just like @Sampath mentioned, one way would be to use a custom provider. But since you method is just a simple one, I think you can use Events instead. It'd be like this:
In your
app.component.ts
file, subscribe to the new event:And then in any other page, just publish the event to execute that logic:
You can use
Directive
.Try as follows.
Put the following code in separate directive file. (social-sharing.directive.ts);
Import it into
app.module.ts
and than add todeclarations
.In HTML, just add
attribute
to any element which is theselector
in your directive file.Additional Info:
Passing values from component to directive.
home.html
home.component.ts
social-sharing.directive.ts
Import
Input
along with others from@angular/core
.Using Element in Directive:
social-sharing.directive.ts
Import
ElementRef
along with others from@angular/core