Search code examples
angulartypescriptngx-bootstrap

Angular TemplateRef Issue


I have to place all the ngx-bootstrap modals in a single component.html so that I can access any modal from anywhere.

I have tried the below code in

header.componentn.html
<button (click)="Login(loginModal)">Login</button>

header.cmponent.ts
@Input() myModal: AppModalsComponent;
bsModalRef: BsModalRef;
Login(template:TemplateRef<any>) {
    this.myModal.openModal(template);
}

app-modals.component.html
<ng-template #loginModal>
    <div class="modal-body">Login Here</div>
 </ng-template>

app-modals.component.ts
openModal(template: TemplateRef<any>) {
    this.modalRef = this.modalService.show(template, this.config);
}

Complete code at StackBlitz.

I'm pasing a template Reference object from HTML. It is getting undefined in ts. I think this is bexause the corresponding ng-template is not present in same HTML. How to reslove this?


Solution

  • According to the documentation you call show() on the modal service and

    Pass a TemplateRef or a component as a first argument and config as a second (optionally).

    To make sharing these modals easier I would just make each modal it's own component. You will need to make sure you declare it as an entryComponent in the app.module.

    Then in whichever component needs to open the modal you can just inject the modal service and then pass the ModalComponent you want it to create.

    modal.component.ts

    @Component({
      selector: 'app-modal',
      template: '<div class="modal-body">Login Here</div>'
    })
    export class ModalComponent {}
    

    some.componet.ts

    @Component({
      selector: 'app-some',
      template: '<button (click)="openModal">Open the modal</button>'
    })
    export class SomeComponent {
      constructor(public modalService: BsModalService) { }
    
      openModal() {
        this.modalService.show(ModalComponent);
      }
    }
    

    Stackblitz