我想从组件中显示模态。 我有一个使用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 . **/
}
}
答案 0 :(得分:7)
首先,您必须向ViewChild
添加open
模板和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 :(得分:1)
对于我自己,我使用Primeng Dialog模块组件。你可以在这里查看: https://www.primefaces.org/primeng/#/dialog
这是一个非常容易使用,看起来非常好,我肯定会推荐它。
答案 2 :(得分:1)
您可以使用@ angular / material打开模式窗口:
https://www.ahmedbouchefra.com/angular/angular-9-8-material-modal-example-and-tutorial/
这很容易,而且您不必使用引导程序:)