Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to open modal from component

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

    }
}
like image 255
has van Avatar asked Aug 18 '17 14:08

has van


People also ask

How do you open modal from another component react?

Set up the Modal ComponentInside the App component, add a button that will open up the modal. In the handleShow() function, set a Boolean state value to true and use it to display or trigger the modal. Now, add the Modal component after the button.


1 Answers

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 :)

like image 175
Fabian R Avatar answered Sep 20 '22 14:09

Fabian R