Home > Software design >  ngx-bootstrap Angular 12 Open modal from another component
ngx-bootstrap Angular 12 Open modal from another component

Time:09-16

I'm trying to create a common ngx-bootstrap modal component in Angular.

I've searched the internet and tried this way.

import { Component } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';

/* This is the Component from which we open the Modal Component */
@Component({
  selector: 'my-component',
  templateUrl: './service-component.html'
})
export class MyComponent {
  bsModalRef: BsModalRef;
  constructor(private modalService: BsModalService) {}

  public openModalWithComponent() {
    /* this is how we open a Modal Component from another component */
    this.bsModalRef = this.modalService.show(ModalContentComponent);
  }
}

/* This is the Modal Component */
@Component({
  selector: 'child-modal',
  template: `
    <div class="modal-header">
      <h4 class="modal-title pull-left">Title</h4>
      <button type="button" class="close pull-right" aria-label="Close" (click)="bsModalRef.hide()">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      ...
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" (click)="bsModalRef.hide()">Close</button>
    </div>
  `
})
export class ChildModalComponent {
  constructor(public bsModalRef: BsModalRef) {}
}

<button type="button" class="btn btn-primary" (click)="openModalWithComponent()">Create modal with component</button>

<child-modal #childModal ></child-modal>

But it says 'Cannot find name 'ModalContentComponent'.

And I really don't understand where they get that from, although it seems to work for other people.

CodePudding user response:

Basically, you create a new component called ModalContentComponent - just use the CLI to do this:

ng generate component /path/modal-content

then import the newly created ModalContentComponent as usual wherever you reference it in your .ts code (e.g. the code you've given in your question) and voila!

Obviously make sure you declare ModalContentComponent in your module in the usual manner (if you have things setup correctly the CLI should handle this for you)

OPTIONAL ADDITIONAL INFO:

To make modals more reusable you probably want the HTML in modal content component to use content projection, which would involve using an additional component that supports content projection.

CodePudding user response:

Please go through this demo https://angular-ngx-bootstrap-alert-osq1c2.stackblitz.io and for code https://stackblitz.com/edit/angular-ngx-bootstrap-alert-osq1c2?file=app/app.module.ts Here you will get whats your mistake(Addition of ModalContentComponent).

  • Related