how to open modal from component

has van picture has van · Aug 18, 2017 · Viewed 15.5k times · Source

I want to display a modal from component . I have a modal component created with ng-bootstrap like follow (just a body):

<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);
        });
    }
}

I really want to be able to open this modal from a component

See my 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 . **/

    }
}

Answer

Fabian R picture Fabian R · Dec 20, 2017

First of all you have to add a ViewChild of the template and one change in the open-method to your 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);
        });
    }
}

Furthermore you have to add a reference in your home.component.html:

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

Now we have to add this reference to your HomeComponent:

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

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

I hope it works :)