1

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.

Lin Du
  • 88,126
  • 95
  • 281
  • 483
coloraddict
  • 113
  • 1
  • 12
  • Does this answer your question? [Property '...' has no initializer and is not definitely assigned in the constructor](https://stackoverflow.com/questions/49699067/property-has-no-initializer-and-is-not-definitely-assigned-in-the-construc) – Yong Shun Jun 21 '21 at 03:46

1 Answers1

1

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

Yong Shun
  • 35,286
  • 4
  • 24
  • 46