ngx-bootstrap modal - 属性 'modalRef' 没有初始化器,并且在构造函数中没有明确分配

时间:2021-06-20 13:49:47

标签: angular ngx-bootstrap

组件:

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' 没有初始化器,也没有在构造函数中明确赋值

提前致谢。

1 个答案:

答案 0 :(得分:1)

提示此警告是因为 strictPropertyInitialization 在 tsconfig.json 中启用 并且您未初始化 modalRef 的值。

<块引用>

属性 'modalRef' 没有初始化器,也没有在构造函数中明确赋值

同时,您不应在 openModal 内定义 constructor 函数。当其他组件需要调用此方法显示模态时,此方法将无法访问。


解决方案

  1. 如果不想初始化modalRef,可以这样做:
modalRef?: BsModalRef;
  1. 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);
    }
}

参考文献

Ngx-Bootstrap - Modals