Friday 20 January 2017

Bootstrap Modal in Angular 2

To use the bootstrap modal in the angular 2 application use ng2-bootstrap
include ng2-bootstrap and moment in your package.json and hit npm install to install both in the node_modules
include modal module in your module file. The app.module.ts file will be,
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ModalModule } from 'ng2-bootstrap/ng2-bootstrap';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { BootstrapModalComponent } from './bootstrap-modal.component';

@NgModule({
  imports:      [ BrowserModule, ModalModule],
  declarations: [ AppComponent, BootstrapModalComponent ],
  bootstrap:    [ AppComponent ]
})

export class AppModule { }
    
Write the bootstrap modal in html and write the functionality in the ts file like
<div class="container">
        <button type="button" class="btn btn-default" (click)="showModal()">Open</button>
    </div>
    <div bsModal #bootstrapModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="bootstrapModal"
    aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" aria-label="Close" (click)="closeModal()">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">Bootstrap modal</h4>
            </div>
            <div class="modal-body">
                <p>This is bootstrap modal</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" (click)="closeModal()">Close</button>
            </div>
        </div>
    </div>
</div>
    
import { Component, OnInit, ViewChild } from '@angular/core';
import { ModalDirective } from 'ng2-bootstrap/ng2-bootstrap';

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

export class BootstrapModalComponent {
    
    @ViewChild('bootstrapModal') public bootstrapModal:ModalDirective;

    constructor() {        
    }

    showModal(){
        this.bootstrapModal.show();
    }

    closeModal(){
        this.bootstrapModal.hide();
    }

}
    

No comments:

Post a Comment