ionic 2 - 如何从父级访问组件功能

时间:2016-12-03 10:47:13

标签: cordova typescript ionic2

我有自定义加载(SearchingModalComponent) 我想调用SearchingModalComponent中的函数show()

SearchingModalComponent

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

@Component({
    selector: 'searching-modal',
    templateUrl: 'searching-modal.html'
})
export class SearchingModalComponent {
    public show_classname: any;

    constructor() {
        this.show_classname = ""
    }

    public show() {
        this.show_classname = "busy";
    }

    hide() {
        this.show_classname = "";
    }
}

app.modules.ts

import { SearchingModalComponent } from '../components/searching-modal/searching-modal';

@NgModule({
    declarations: [
        MyApp,
        HomePage,
        ScanPage,
        SearchingModalComponent
    ],
    imports: [
        IonicModule.forRoot(MyApp)
    ],
    bootstrap: [IonicApp],
    entryComponents: [
        MyApp,
        HomePage,
        ScanPage
    ],
    providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}, [ScreenSaver]]
})
export class AppModule {}

app.component.ts

@Component({
    template: `
        <ion-nav [root]="rootPage"></ion-nav>
        <searching-modal id="loading" #Searching></searching-modal>
    `
})

根页

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { SearchingModalComponent } from '../../components/searching-modal/searching-modal';

@Component({
    selector: 'page-scan',
    templateUrl: 'scan.html'
})
export class ScanPage {

    constructor(public navCtrl: NavController
    , public ScreenSaverPrivid: ScreenSaver
    , public SearchingModal: SearchingModalComponent
    ) { }

    openLoading() {
        this.SearchingModal.show();
        console.log('openLoading');
    }
}
  

系统信息:

     
      
  • Cordova CLI:6.0.0
  •   
  • Ionic Framework版本:2.0.0-rc.3
  •   
  • Ionic CLI版本:2.1.14
  •   
  • Ionic App Lib版本:2.1.7
  •   
  • Ionic App Scripts版本:0.0.46
  •   
  • ios-deploy版本:未安装
  •   
  • ios-sim版本:未安装
  •   
  • 操作系统:Windows 10
  •   
  • 节点版本:v6.9.1
  •   
  • Xcode版本:未安装
  •   

修改 [已解决] 谢谢 Hadrien TOMA

  

移动<searching-modal id="loading" #Searching></searching-modal>
  至   scan.html

1 个答案:

答案 0 :(得分:1)

您只需使用ViewChild并在您的父模板中添加您孩子的参考(正如您已经完成的那样),here您可以看到一个如何执行此操作的简单示例。

编辑:添加一些提示

此外,您必须在相对于具有引用的模板的组件中调用@ViewChild,在您的情况下,您有两个选项:将<searching-modal id="loading" #Searching></searching-modal>移至scan.html或移动{{ 1}}和openLoading(){...}@ViewChild(...)...。第一个选择对我来说是最好的。