cloude
cloude

Reputation: 346

Call function in app.component from page.ts [IONIC4]

If I have a function in:

results.ts

export class ResultsPage implements OnInit {

    myFunc() {
       alert('my function works!');
    }

}

app.component.html

<button (click)="myFunc()">CALL</button>

can I call this function in my app.component.html?

Upvotes: 0

Views: 2931

Answers (1)

parrycima
parrycima

Reputation: 945

You should use angular providers and services

run ionic g service SomeProvider

inside SomeProvider create your function

import { Injectable } from '@angular/core';

@Injectable()
export class SomeProvider {

    constructor() {

    }

    someFunction(){
        console.log("I do something useful!");
    }

}

set up as a provider in the app.module.ts file:

@NgModule({
  declarations: [
    MyApp
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp
  ],
  providers: [
    SomeProvider // <-- List providers here
  ]
})
export class AppModule { }

inject into classes that want to use them:

import { Component } from '@angular/core';
import { IonicPage } from 'ionic-angular';
import { SomeProvider } from '../../providers/some-provider/some-provider';

@IonicPage()
@Component({
  selector: 'page-something',
  templateUrl: 'something.html',
})
export class SomePage {
    constructor(public myService: SomeService) {

    }

    ionViewDidLoad() {
        this.myService.someFunction(); // This will log "I do something useful!"
    }

}

Here you can find complete guide: https://www.joshmorony.com/when-to-use-providersservicesinjectables-in-ionic/

Upvotes: 1

Related Questions