How can I put an Ionic 2 Modal in a separate file?

2019-08-26 20:40发布

问题:

I'm using Ionic 2 and want to use a Modal for different pages.

One use case is the creation and editing of messages: I want to display a "new message" button on the dashboard page, another "new message" button on the messages list page and a third button "edit message" on the message view page. All of those buttons should open the same MessagesEditModal.

My current code looks like that:

import { Component } from '@angular/core';
import { Modal, NavController, ViewController } from 'ionic-angular';

@Component({
    templateUrl: 'build/pages/messages/messages-list-page.html'
})
export class MessagesListPage {

    static get parameters() {
        return [[NavController]];
    }

    constructor(navController, sessionsService) {
        this.navController = navController;
    }

    showModal() {
        let modal = Modal.create(MessagesEditModal, { some: "data" });
        this.navController.present(modal);
    }

}

@Component({
    templateUrl: 'build/pages/messages/messages-edit-modal.html'
})
class MessagesEditModal {

    static get parameters() {
        return [ViewController];
    }

    constructor(viewCtrl) {
        this.viewCtrl = viewCtrl;
    }

    close() {
        this.viewCtrl.dismiss();
    }

}

This works fine for one page, but I want to reuse this modal in other pages. I've tried to put the "MessagesEditModal" class into a separate file and added an import for it, but this fails. When I call showModal() this exception gets thrown:

ORIGINAL EXCEPTION: TypeError: componentType is undefined

How can I use a Modal from different pages?

I don't want to use a page here because the content really should be displayed and behave like a modal behaves (animation and non-fullscreen on tablets).

回答1:

This works fine for one page, but I want to reuse this modal in other pages. I've tried to put the "MessagesEditModal" class into a separate file and added an import for it, but this fails.

When you did that, did you also add the export keyword in the MessagesEditModal class definition?

@Component({
    templateUrl: 'build/pages/messages/messages-edit-modal.html'
})
export class MessagesEditModal {

    static get parameters() {
        return [ViewController];
    }

    constructor(viewCtrl) {
        this.viewCtrl = viewCtrl;
    }

    close() {
        this.viewCtrl.dismiss();
    }

}