我想从组件中显示一个模态.
我有一个使用ng-bootstrap创建的模态组件,如follow(只是一个正文):
我有一个使用ng-bootstrap创建的模态组件,如follow(只是一个正文):
< template id =“accept”#content let-c =“close”let-d =“dismiss”>
< div class =“modal-body”>
< p>模态体< / p>
< / DIV>
< /模板>
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 . **/ } }
解决方法
首先,您必须添加模板的ViewChild,并将open-method中的一个更改添加到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(); } }
我希望它有效:)