Setup Bootstrap in angular & Open Modal Dialog

In these article we discuss on how to setup bootstrap in our application. For adding bootstrap i found lots packages available. i have found one good package called “ngx-bootstrap”. For install “ngx-bootstrap” use below command.

npm install ngx-bootstrap --save

After run above command we need to add the bootstrap CSS in our index.html file.


<!--- index.html -->
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet">

after adding CSS now its ready to use bootstrap in our application.
For Using Modal Dialog first we need to add “import { ModalModule } from ‘ngx-bootstrap’;” in our main app.module.ts file and import that in @NgModule.


....
import { ModalModule } from 'ngx-bootstrap';
....
@NgModule({
........
imports: [
  ModalModule.forRoot(),
],
........

})
export class AppModule(){}

Open a modal using Service
First we need to inject “BsModalService” in your component. Then call show() method of modal service and pass template reference in it.
In component first we need to add below code in your component.



import { Component, TemplateRef } from '@angular/core';
import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/bs-modal-ref.service';

@Component({
  selector: 'open-modal-component',
  templateUrl: './template.html'
})

export class OpenModalComponent {
  modalRef: BsModalRef;
  constructor(private bsmodalservice: BsModalService) {}
 
  open(template: TemplateRef) {
    this.modalRef = this.bsmodalservice.show(template);
  }
}



In our “template.html” file we need to add the button for the open popup and add template for the popup.


<button type="button" class="btn btn-primary" (click)="open(template)">Create template modal</button>
<ng-template #template>
  <div class="modal-header">
    <h4 class="modal-title pull-left">Modal</h4>
    <button type="button" class="close pull-right" aria-label="Close" (click)="modalRef.hide()">
      <span aria-hidden="true">×</span>
    </button>
  </div>
  <div class="modal-body">
    This is a modal.
  </div>
</ng-template>

These easy way you can open modal in our angular app.

Spread the love
  • 30
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •