如何从组件中打开模态

问题描述 投票:3回答:2

我想从组件中显示一个模态。我有一个使用ng-bootstrap创建的模态组件,如follow(只是一个正文):

<template id="accept" #content let-c="close" let-d="dismiss"> <div class="modal-body"> <p>Modal body</p> </div> </template>

import { Component } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
    selector: 'my-hello-home-modal',
    templateUrl: './hellohome.modal.html'
})

export class HelloHomeModalComponent {
    closeResult: string;

    constructor(private modal: NgbModal) {}

    open(content) {
        this.modal.open(content).result.then((result) => {
            this.closeResult = `Closed with: ${result}`;
        }, (reason) => {
            console.log(reason);
        });
    }
}

我真的希望能够从组件中打开这个模态

看我的homeComponent

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

@Component({
    selector: 'my-home',
    templateUrl: './home.component.html'
})

export class HomeComponent implements OnInit {
    constructor() {
    }

    timer() {
        /** want to open this modal from here . **/

    }
}
angular ng-bootstrap
2个回答
6
投票

首先,您必须添加模板的ViewChildopen方法中的一个更改到您的HelloHomeModalComponent

export class HelloHomeModalComponent {
    // add reference of the template
    @ViewChild('content') content: any;

    closeResult: string;

    constructor(private modal: NgbModal) {}

    // remove the parameter "content"
    open() {
        // and use the reference from the component itself
        this.modal.open(this.content).result.then((result) => {
            this.closeResult = `Closed with: ${result}`;
        }, (reason) => {
            console.log(reason);
        });
    }
}

此外,您必须在home.component.html中添加引用:

...
<!-- add the #myModal -->
<my-hello-home-modal #myModal></my-hello-home-modal>
...

现在我们必须将此引用添加到您的HomeComponent

export class HomeComponent implements OnInit {
    // add ViewChild
    @ViewChild('myModal') modal: HelloHomeModalComponent;
    constructor() {
    }

    timer() {
        // open the modal
        this.modal.open();
    }
}

我希望它有效:)


1
投票

对于我自己,我使用Primeng Dialog模块组件。你可以在这里查看:https://www.primefaces.org/primeng/#/dialog

这是一个非常容易使用,看起来非常好,我肯定会推荐它。

© www.soinside.com 2019 - 2024. All rights reserved.