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 . **/
}
}
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With