gpt4 book ai didi

angular - 调用 NgbModal open 方法的最佳实践

转载 作者:太空狗 更新时间:2023-10-29 17:04:47 25 4
gpt4 key购买 nike

玩转 NgbModal并想触发打开方法 -> open(content: string | TemplateRef<any>, options: NgbModalOptions) <- 来自模板代码以外的其他地方。在我的例子中,我想在我的组件的 .ts 文件中运行该方法时传递一个字符串作为参数。当通过 html 文件中的按钮运行该方法时,如下所示:<button (click)="open(content)">Launch demo modal</button> ,代码工作得很好,当然所有代码都来自 <template></template>在 html 文件中。

试图用这个完成一些事情:

logoutScreenOptions: NgbModalOptions = {
backdrop: 'static',
keyboard: false
};

lockedWindow: NgbModalRef;

lockedScreenContent= `
<template #content let-c="close" let-d="dismiss">
<div class="modal-header" style="text-align: center">
<h3 class="modal-title">Title</h3>
</div>
<div class="modal-body">
<p>Body</p>
</div>
<div class="modal-footer">
<p>Footer</p>
</div>
</template>
`;

openLockedScreen(){
this.open(this.lockedScreenContent);
}

open(content) {
console.log(content);
this.lockedWindow = this.modalService.open(content, this.logoutScreenOptions);
this.lockedWindow.result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {
this.closeResult = `Dismissed ${this.getDismissReason(reason)}`;
});
}

代码运行没有错误,模式打开如下: Modal without rendered content...这不是我想要的!

也这样试过,结果完全一样:

lockedScreenContent= `
<div class="modal-header" style="text-align: center">
<h3 class="modal-title">Title</h3>
</div>
<div class="modal-body">
<p>Body</p>
</div>
<div class="modal-footer">
<p>Footer</p>
</div>
`;

我错过了什么?难道不能只传递一个字符串作为“内容”参数吗?

我也不知道如何使用 ts 文件中的 templateRef 参数!

最佳答案

截至今天 open https://ng-bootstrap.github.io/#/components/modal的方法具有以下签名:open(content: string | TemplateRef<any>, options: NgbModalOptions) .从这个签名中可以看出,您可以打开一个提供内容的模态:

  • string
  • TemplateRef

string -typed 参数不是很有趣——事实上,它主要是为了帮助调试/单元测试而添加的。通过使用它,你可以只传递......好吧,一段文本,没有任何标记而不是 Angular 指令。因此,它实际上是一个调试工具,而不是在现实生活场景中有用的东西。

TemplateRef参数更有趣,因为它允许您传递要显示的标记+指令。你可以得到一个TemplateRef的手通过做<template #refVar>...content goes here...</template>组件模板中的某处(您计划从中打开模态的组件模板)。因此 TemplateRef参数很强大,因为它允许您拥有标记、指令、其他组件等。缺点是 TemplateRef仅当您从带有模板的组件打开模式时才有用。

我的印象是您正在寻找已计划但尚未实现的功能 - 能够打开以组件类型作为内容的模式。它将按如下方式工作:modalService.open(MyComponentWithContent) .正如我所提到的,这是路线图的一部分,但尚未实现。您可以通过关注 https://github.com/ng-bootstrap/ng-bootstrap/issues/680 跟踪此功能

关于angular - 调用 NgbModal open 方法的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39464345/

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