@ng-bootstrap | Pass Data to a Bootstrap Modal Dialog using Angular

Angular tutorial on How to pass data from parent component to Bootstrap modal and get back response to the parent component.

Note: This tutorial is compatible with Angular version 6,7,8 and 9

The ng-bootstrap package provides the bootstrap components for Angular projects which makes the implementation of bootstrap components in an Angular project very easy.

In this tutorial, we will discuss how to implement Bootstrap modals in an Angular project using the ng-bootstrap package and also get to know about how to pass data from parent component in modal and also how we can get back data to parent component from modal.

To pass and get back data from Bootstrap modals does not require any special arrangements, these communications are beautifully handled by bootstrap modal methods.

Here we will first install ng-bootstrap in a new Angular project and then learn how to add NgBootstrap modals.

Adding Ng-bootstrap in Angular Project

First, to use bootstrap modals, let’s quicky install bootstrap to Angular project:

Run following NPM command in terminal:

$ npm install --save @ng-bootstrap/ng-bootstrap

Now open the app.module.ts file then add in imports array as shown below:

import {NgbModule} from '@ng-bootstrap/ng-bootstrap';

@NgModule({
  ...
  imports: [NgbModule, ...],
  ...
})
export class YourAppModule {
}

Next, add Bootstrap.css in Project. The best method is to include it in index.html file's head section:

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>Angular Project</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
</head>

<body>
  <app-root></app-root>
</body>

</html>

Create a New Modal Component

In a real-world application, we usually prefer to have a different component which we want to show a modal component.

So here we will create a new component MyBootstrapModalComponent in modals folder to easily recognize all application modals.

Run the following generate command in terminal to create it using ng cli tool:

$ ng generate component modals/MyBootstrapModal

In the app.module.ts file, the above command will automatically add to declarations array but you also need to add it to the entryComponets array as this is added dynamically:

...
...
@NgModule({
  declarations: [
    AppComponent,
    ....
    ....
    MyBootstrapModalComponent
  ],
  entryComponents:[
    MyBootstrapModalComponent
  ],
...
...

 

 

we will modify this modal later in this tutorial, first let's open this modal and pass some data from app component.

Open Modal and Pass Data from Component

As our modal component is ready, let's add the openModal method in the app.component.ts file which can be called by a simple button template:

<button class="btn" (click)="openModal()"></button>

In the app.component.ts file replace below code to open modal using openModal method:

// app.component.ts
import { Component } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { MyBootstrapModalComponent } from './modals/my-bootstrap-modal/my-bootstrap-modal.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular-bootstrap-modal';

  constructor(
    private modalService: NgbModal,
  ) {
  }


  openModal() {
    const modalRef = this.modalService.open(MyBootstrapModalComponent,
      {
        scrollable: true,
        windowClass: 'myCustomModalClass',
        // keyboard: false,
        // backdrop: 'static'
      });

    let data = {
      prop1: 'Some Data',
      prop2: 'From Parent Component',
      prop3: 'This Can be anything'
    }

    modalRef.componentInstance.fromParent = data;
    modalRef.result.then((result) => {
      console.log(result);
    }, (reason) => {
    });
  }
}

To open bootstrap modal with the component we call the open method of NgbModal class.

It also takes some configuration properties:

 backdrop: If `true`, the backdrop element will be created for a given modal. Alternatively, specify `'static'` for a backdrop that doesn't close the modal on click. The default value is `true`.

beforeDismiss: Callback right before the modal will be dismissed.

centered: If `true`, the modal will be centered vertically. The default value is `false`.

container: A selector specifying the element all-new modal windows should be appended to. If not specified, it will be `body`.

keyboard: If `true`, the modal will be closed when the `Escape` key is pressed. The default value is `true`.

scrollable: Scrollable modal content (false by default).

size: Size of a new modal window. 'sm' | 'lg' | 'xl' | string;

windowClass: A custom class to append to the modal window.

backdropClass: A custom class to append to the modal backdrop.

Using componetInstance we can pass data object to modal contents.

Modify Modal and Get Data from Parent

To get data from parent component which we passed in the open method, we use @Input decorator.

In the my-bootstrap-modal.component.ts file, replace below code:

// my-bootstrap-modal.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';

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

  @Input() fromParent;

  constructor(
    public activeModal: NgbActiveModal
  ) { }

  ngOnInit() {
    console.log(this.fromParent);
    /* Output:
     {prop1: "Some Data", prop2: "From Parent Component", prop3: "This Can be anything"}
    */
  }

  closeModal(sendData) {
    this.activeModal.close(sendData);
  }

}

We can close the modal using the NgbActiveModal class method close and also pass any data to send back to the parent component's result block.

In the my-bootstrap-modal.component.html file just place below HTML template to show modal content with dynamic data passed from parent component:

<div class="modal-header">
    <h5 class="modal-title">Modal title</h5>
    <button type="button" class="close" data-dismiss="modal" (click)="closeModal('dismiss')">
        <span aria-hidden="true">&times;</span>
    </button>
</div>
<div class="modal-body">
    <p>Modal body text goes here.</p>
    <p>{{ fromParent | json }}</p>
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-secondary" data-dismiss="modal" (click)="closeModal('close')">Close</button>
    <button type="button" class="btn btn-primary" (click)="closeModal('changes saved!')">Save changes</button>
</div>

That's it above we got to know how to easily open a component as a bootstrap modal and how we can communicate between parent component and model by passing data between them.

Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments