Saturday 18 November 2017

Modal in a Bootstrap Angular 4 application using ng2-bootstrap-modal

Note: This is for folks not using the angular-bootstrap.


Challenge:

The usual javascript libraries would not integrate very well with the other Angular components. I needed the modal to take up arguments from the parent component and also pass back information to the parent once it has done a AJAX call ( HTTP-Post ). The main challenge I did face was documentation which was not available in one place.

Library Used:

ng2-bootstrap-modal  from ( https://www.npmjs.com/package/ng2-bootstrap-modal )

To Start:

  1. Get the NPM module installed.

-> npm install https://www.npmjs.com/package/ng2-bootstrap-modal



      2. Create the Modal Component required for your purpose

-> ng generate component myModal  ( this will add the component to app.module.ts as well )

      3. Changes in the app.module.ts


-> import { BootstrapModalModule } from 'ng2-bootstrap-modal';

-> Add "BootstrapModalModule" in the imports

-> Add your component to the entryComponents under the NgModule using:
     entryComponents: [MyModalComponent]

     4. Changes in myModal.component.ts

->  Add : import { DialogComponent, DialogService } from "ng2-bootstrap-modal";

-> Create the interface  and export
export interface MyModel {
  idList: number[];
  title:string;
}

-> Change the myModalComponent to extend the dialogComponent
export class MyModalComponent extends DialogComponent<MyModel, number> implements MyModel{ 
  idList: number[];
  title:string;

-> Have the constructor extend the DialogService using super() call
  constructor(dialogService: DialogService) {
    super(dialogService);
    this.jobId = 0;
  }

-> Create a close function and also functions for the different actions in the modal as required and link it to the html just like any other constructor. The important thing to remember here is to have this.result set to the result and to close() the modal once the action is done.

  cancel() {
    this.result = -1;
    this.close();
  }


    5. Changes to the calling component

-> Import the dialog service
import { DialogComponent, DialogService } from "ng2-bootstrap-modal";

-> Import the modal Component
import {MyModalComponent} from '../my-modal/myModal.component';

-> In the click function where we need the modal to appear, add this line to call the Dialog-Component with the necessary arguments //CheckStatus is my click call-back
 checkStatus() {
    this.dialogService.addDialog(MyModalComponent,{idList:[1,2,3], title: 'Availability'});

  }