How to create a reusable confirmation Modal component in Angular
Step 1: Setting up the application
Let’s start by installing Angular
npm install -g @angular/cli
Creating a brand new Angular application
ng new angular-reusable-modal
Open the project directory
cd angular-reusable-modal
Open the project using VS Code
code .
Adding ng-bootstrap to the angular project
ng add @ng-bootstrap/ng-bootstrap
Step 2: Creating our Confirmation Modal Component
Project File Structure
Create Shared Module
Create a folder called shared and module file as shared.module.ts. The created module can be used to add your reusable components. In this folder, you can manage your reusable components easily.
Now go to the app.module.ts and import the SharedModule
Create our Confirmation Modal Component
Go to the shared directory and generate the confirmation modal using,
ng g c confirmation-modal
Now you can add the following codes to the confirmation-modal component.
Step 3: Using our Modal Component
Now you can use the modal easily since the component is injectable, we only need to include the <confirmation-modal>
tag in the .html file of the component where you want to include the modal. The tag will look like this:
add .html,
<confirmation-modal #confirmationModal (newConfirmationEvent)="getConfirmationValue($event)" [modalStyle]="modalStyle"
[modalTitle]="modalTitle"
[modalBody]="modalBody"
[modalButtonColor]="modalButtonColor"></confirmation-modal>
add .ts,
@ViewChild('confirmationModal')
private modalComponent!: ConfirmationModalComponent;modalStyle: string = 'modal-style-primary';
modalTitle: string = 'Info Confirmation';
modalBody: string = 'This is a Information Confirmation message';
modalButtonColor: string = 'btn-primary';async openModal() {
return await this.modalComponent.open();
}
you can use this modal component to show your all confirmation. Also, you can change the modal style, title, body
Final Step:: Create Delete Confirmation Using our Modal Component
I have used this modal component in the app component. but you can use any component like this,
Conclusion
That’s the end of this tutorial on how to create reusable modal components in Angular and ng-bootstrap. comments and suggestions are welcome.
One Code Can Change Your Project !!