组件:
import { Component, OnInit, TemplateRef } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
export class PatchListComponent implements OnInit {
modalRef: BsModalRef;
constructor(private modalService: BsModalService) {
openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template);
}
}
}
模块:
import { ModalModule } from 'ngx-bootstrap/modal';
@NgModule({
declarations: [
MyComponent
],
imports: [
ModalModule.forRoot(),
]
})
export class MyModule { }
出现以下错误:
<块引用>属性 'modalRef' 没有初始化器,也没有在构造函数中明确赋值
提前致谢。
答案 0 :(得分:1)
提示此警告是因为 strictPropertyInitialization 在 tsconfig.json 中启用 并且您未初始化 modalRef
的值。
属性 'modalRef' 没有初始化器,也没有在构造函数中明确赋值
同时,您不应在 openModal
内定义 constructor
函数。当其他组件需要调用此方法显示模态时,此方法将无法访问。
modalRef
,可以这样做:modalRef?: BsModalRef;
openModal
中移出 constructor
函数。component.ts
import { Component, OnInit, TemplateRef } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
export class PatchListComponent implements OnInit {
modalRef?: BsModalRef;
constructor(private modalService: BsModalService) {}
openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template);
}
}