gpt4 book ai didi

Angular 7 + NG Bootstrap,从服务打开模式?

转载 作者:行者123 更新时间:2023-12-04 15:52:34 26 4
gpt4 key购买 nike

我是 Angular 的新手,我正在尝试创建一个检查本地存储的服务,如果所需的 key 不存在,则打开一个模态框,要求输入一个名称来创建该本地存储 key 。

但是,模态打开但我只看到“禁用”背景而不是模态信息。

我不知道我做错了什么,我找不到很多关于这个的信息。

不知道服务是否是执行此操作的正确方法,我需要一些帮助。此外,服务依赖于其他服务是一种好做法吗?

代码如下:

import { Injectable } from '@angular/core';
import { NgbModal, ModalDismissReasons } from '@ng-bootstrap/ng-bootstrap';
import { localStorageService } from './localStorage.service';

let template: `<ng-template #content let-modal let-c="close" let-d="dismiss">
<div class="modal-header">
<h4 class="modal-title">Insert Your Name</h4>
</div>
<div class="modal-body">
<form>
<div class="input-group">
<input [(ngModel)]='name' id="name" class="form-control" name="name">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-outline-dark" (click)="saveName(name);c('Save Click')">Save</button>
</div>
</ng-template>`

@Injectable({
providedIn: 'root'
})

export class CheckuserService {

private closeResult: String;

constructor(private modalService: NgbModal, private lss: localStorageService, ) { }

test() {
if (this.lss.getStorage() !== "null") {
this.modalService.open(template, { ariaLabelledBy: 'modal-basic-title' }).result.then((result) => {
this.closeResult = `Closed with: ${result}`;
}, (reason) => {

});
} else {
console.log("Already logged")
}
}


}

最佳答案

抱歉 - 我在评论中没有注意到您从服务中打开模板并且模板是一个字符串

如果您查看 NgBoostrap 的文档 - 它会打开一个 TemplateRef 或一个 Component 类型 - 而不是一个字符串。

open open(content: any, options: NgbModalOptions) => NgbModalRef

Opens a new modal window with the specified content and using supplied options. Content can be provided as a TemplateRef or a component type. If you pass a component type as content than instances of those components can be injected with an instance of the NgbActiveModal class. You can use methods on the NgbActiveModal class to close / dismiss modals from "inside" of a component.

当您引用 <ng-template> 时在像
这样的组件中 ViewChild('tplRef', {read: TemplateRef}) myTplRef: TemplateRef;

它创建一个 TemplateRef 对象(您稍后将其传递给 NgBootstrap 模态服务)。另一方面,您要做的是传递一个字符串 - NgBootstrap 不支持。

因此,您应该在调用服务时将模板引用/组件作为参数传递。

关于Angular 7 + NG Bootstrap,从服务打开模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53263616/

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