Search code examples
angularngx-bootstrap

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


Component:

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);
       }
   }
}

Module:

import { ModalModule } from 'ngx-bootstrap/modal';

@NgModule({
  declarations: [
    MyComponent
  ],
  imports: [
    ModalModule.forRoot(),
  ]
})
export class MyModule { }

Getting the following error :

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

Thanks in advance.


Solution

  • This warning is prompted as strictPropertyInitialization is enabled in tsconfig.json and you don't initialize the value for modalRef.

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

    Meanwhile, you should not define openModal function inside constructor. This method will be inaccessible when another component needs to call this method for showing modal.


    SOLUTION

    1. If you don't want to initialize modalRef, you can do in this way:
    modalRef?: BsModalRef;
    
    1. Move out openModal function from 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);
        }
    }
    

    REFERENCES

    Ngx-Bootstrap - Modals