gpt4 book ai didi

angular - 如何从组件打开模态

转载 作者:太空狗 更新时间:2023-10-29 17:46:21 26 4
gpt4 key购买 nike

我想显示来自组件的模式。我有一个使用 ng-bootstrap 创建的模态组件,如下所示(只是一个主体):

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

}
}

最佳答案

首先,您必须添加模板的 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();
}
}

我希望它有效:)

关于angular - 如何从组件打开模态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45759316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com