【问题标题】:ngx-bootstrap modal - Property 'modalRef' has no initializer and is not definitely assigned in the constructorngx-bootstrap modal - 属性 'modalRef' 没有初始化器,并且没有在构造函数中明确分配
【发布时间】:2021-09-04 10:47:46
【问题描述】:

组件:

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

提前致谢。

【问题讨论】:

标签: angular ngx-bootstrap


【解决方案1】:

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

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

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


解决方案

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

组件.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

【讨论】:

  • 谢谢,它有效。 openModal 函数不在构造函数中
猜你喜欢
  • 2021-08-14
  • 2021-02-28
  • 2021-06-23
  • 2021-04-13
  • 2021-05-21
  • 2021-05-06
  • 2021-11-29
  • 1970-01-01
相关资源
最近更新 更多