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

ngx-bootstrap modal - Property 'modalRef' has no initializer and is not definitely assigned in the constructor

组件:

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 { }

出现以下错误:

Property 'modalRef' has no initializer and is not definitely assigned in the constructor

提前致谢。

出现此警告是因为 strictPropertyInitialization 在 tsconfig.json 中启用并且您 没有初始化 modalRef[= 的值39=].

Property 'modalRef' has no initializer and is not definitely assigned in the constructor

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


解决方案

  1. 如果不想初始化modalRef,可以这样:
modalRef?: BsModalRef;
  1. constructor 移出 openModal 功能。

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