Javascript 无法在一个组件中使用多个ngbModal
我试图在我的角度分量中使用多个ngbModal。我能够成功地打开和关闭第一个模式。我试图打开第二个模型时出错。我怎么能修好它。请引导我 当我点击Test1按钮时,它会显示一个错误。错误类型错误:“this.modalService未定义” HTMLJavascript 无法在一个组件中使用多个ngbModal,javascript,html,angular,Javascript,Html,Angular,我试图在我的角度分量中使用多个ngbModal。我能够成功地打开和关闭第一个模式。我试图打开第二个模型时出错。我怎么能修好它。请引导我 当我点击Test1按钮时,它会显示一个错误。错误类型错误:“this.modalService未定义” HTML 测试1 测试2 TS @ViewChild('firstTemplate',{static:true})firstTemplate:TemplateRef; @ViewChild('secondTemplate',{static:true})se
测试1
测试2
TS
@ViewChild('firstTemplate',{static:true})firstTemplate:TemplateRef;
@ViewChild('secondTemplate',{static:true})secondTemplate:TemplateRef;
@ViewChild('disabledEsc',{read:TemplateRef,static:true})disabledEscTemplate:TemplateRef;
构造函数(私有modalService:NgbModal){}
onClick(事件){
event.srcmelement.blur();
event.preventDefault();
this.modalService.open(this.firstTemplate{
windowClass:“ngb模式”,
大小:“lg”,可滚动:真,居中:真,背景:“静态”,
});
onTest1(活动){
console.log(事件);
event.srcmelement.blur();
event.preventDefault();
setTimeout(this.testModal,500);
}
testModal(){
this.modalService.open(this.secondTemplate,{//错误
windowClass:“ngb模式”,
大小:“lg”,可滚动:真,居中:真,背景:“静态”,
});
}
}
您有一个错误,即未定义modalService,因为当setTimeout执行testModal
方法时,此
上下文未设置为组件的实例
要解决此问题,可以使用箭头功能:
setTimeout(()=>this.testModal(),500);
或者,您可以将testModal函数的此上下文绑定到组件:
const boundTestModal=this.testModal.bind(this);
setTimeout(boundTestModal,500);
<button (click)="onClick($event)"></button>
<ng-template #firstTemplate let-modal>
<div class="modal-footer">
<button type="button" class="btn btn-primary" (click)="onTest1($event); modal.close('Save click')">test1</button>
</div>
</ng-template>
<ng-template #secondTemplate let-modal>
<div class="modal-footer">
<button type="button" class="btn btn-primary" (click)="onTest2($event); modal.close('Save click')">test2</button>
</div>
</ng-template>
@ViewChild('firstTemplate', {static: true}) firstTemplate: TemplateRef<any>;
@ViewChild('secondTemplate', {static: true}) secondTemplate: TemplateRef<any>;
@ViewChild('disabledEsc', {read: TemplateRef, static: true}) disabledEscTemplate: TemplateRef<HTMLElement>;
constructor(private modalService: NgbModal) {}
onClick(event) {
event.srcElement.blur();
event.preventDefault();
this.modalService.open(this.firstTemplate, {
windowClass: 'ngb-modal',
size: 'lg', scrollable: true, centered: true, backdrop: 'static',
});
onTest1(event) {
console.log(event);
event.srcElement.blur();
event.preventDefault();
setTimeout(this.testModal, 500);
}
testModal() {
this.modalService.open(this.secondTemplate, { // error
windowClass: 'ngb-modal',
size: 'lg', scrollable: true, centered: true, backdrop: 'static',
});
}
}