Angular Bootstrap Modals
Modals are dialog boxes that are used to display content or ask for input from the user. In Angular, Bootstrap modals can be easily integrated and customized using the ngx-bootstrap package. Modals in Angular are initialized using a component and can be triggered by clicking a button or link.
Syntax
<button class="btn" (click)="openModal()">Open Modal</button>
<ng-template #myModal>
<div class="modal modal-dialog-centered show" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal Title</h5>
<button type="button" class="close" aria-label="Close" (click)="modalRef.hide()">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Modal Content
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" (click)="modalRef.hide()">Close</button>
<button type="button" class="btn btn-primary" (click)="modalRef.hide()">Save changes</button>
</div>
</div>
</div>
</div>
</ng-template>
Example
import { Component, TemplateRef } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';
@Component({
selector: 'app-modal',
templateUrl: './modal.component.html'
})
export class ModalComponent {
modalRef: BsModalRef;
constructor(private modalService: BsModalService) {}
openModal(template: TemplateRef<any>) {
this.modalRef = this.modalService.show(template);
}
}
Output
The above example will produce a modal with the title "Modal Title", content "Modal Content", and two buttons "Close" and "Save Changes".
Explanation
The Angular Bootstrap Modals use the ngx-bootstrap package to display modal content. The modal is triggered by calling the show()
function of the BsModalService
, which takes a TemplateRef
as an argument. The TemplateRef
contains the HTML markup for the modal.
Use
Modal dialogs can be used in various scenarios when we need to grab a user's attention for some specific action. Modals can be used for:
- User confirmation on various actions, like delete, submit, etc.
- Displaying critical information that needs to be acknowledged by the user before proceeding.
- To display forms or detailed content that should not be on the main page.
Important Points
- Always add an accessible way to close the modal, like a close button or escape key.
- Keep the modal content clear and concise; modal blocks the entire screen.
- Use modal with caution, it can interrupt the user’s flow, and too many modals on a page can be distracting.
Summary
Angular Bootstrap Modals are an excellent tool to display information to users or request confirmation. You can easily create modals in Angular using the ngx-bootstrap package and customize them according to your needs.