Sourav
Sourav

Reputation: 365

In Angular ng-bootstrap modal with template, close and dismiss buttons not working

I am new to angular and I am learning by building.

I have a requirement to open a modal programmatically with varying HTML Content.

I have referred the first stackblitz example illustrated in this issue and created a ModalComponent (with selector called <app-modal>), so that I can create modals anywhere in my app.

Now, I use this component with varying html content in a <ng-template> in my page.

The modal opens fine on clicking the button in the main page, but the close and dismiss buttons in the modal do not work.

I have tried to make a minimal example here : https://stackblitz.com/edit/angular-j1u4fo

Any help will be appreciated. Thanks.

Upvotes: 3

Views: 5131

Answers (2)

Pawan Jangid
Pawan Jangid

Reputation: 175

Try this

I have created Global configuration of modals with let-c="close" and let-d="dismiss"

app.component.html

<div class="container-fluid">
<p>Welcome to {{ name }}</p>
<button type="button" (click)="openModal()">Click to open Modal</button>

<!-- Example 1: Passing TemplateRef as custom component -->
  <ng-template #modal1 let-c="close" let-d="dismiss">
    <app-modal [title]="'Title'" [c]="c" [d]="d">
      <img src="https://angular.io/assets/images/logos/angular/angular.png" height="100px" width="100px">
    </app-modal>
  </ng-template>
</div>

modal.component.html

<div class="modal-header">
    <h4 class="modal-title">{{title}}</h4>
    <button type="button" class="close" aria-label="Close" (click)="d('Cross click')">
        <span aria-hidden="true">&times;</span>
    </button>
</div>
<div class="modal-body">
    <ng-content></ng-content>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-secondary" (click)="c('Close click')">Cancel</button>
</div>

modal.component.ts

import { Component, Input, OnInit } from '@angular/core';

import {NgbModal, NgbActiveModal} from '@ng-bootstrap/ng-bootstrap';


@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {

  @Input() title = `Information`;
  @Input() c;
  @Input() d;

  constructor(
    public activeModal: NgbActiveModal
  ) {}

  ngOnInit() {
  }

}

Upvotes: 3

Kylos
Kylos

Reputation: 1938

Replace this.m1 with ModalComponent in your call to openModal.

According to the API documentation, NgbActiveModal only works when you pass in a component instead of the template.

If you pass a component type as content, then instances of those components can be injected with an instance of the NgbActiveModal class. You can then use NgbActiveModal methods to close / dismiss modals from "inside" of your component.

Upvotes: 0

Related Questions