How to Create Modal in Angular

wordpress featured image

Creating Modal in Angular has been made quite easy with the advent of a lot of component libraries available for the framework. Using 3rd party libraries can cause a lot of bloat in the code-base, and have unnecessary dependencies which may cause problem in the long run. So in this post, we are going to use the Angular’s own Material Design Component to do the same.

Let’s get started.

Creating an Angular Project

Prerequisite: Node, VSCode (or any preferred code editor)

Open up terminal and run:

ng new angular-demo

See how to Create Angular Project

To use Angular Material, we can perform

ng add @angular/material

This is going to ask a few questions for setting-up. Answer them as per your requirements. I have given my selections in bold.

The package @angular/material@x.y.z will be installed and executed.
1. ? Would you like to proceed? y/N – Yes
2. ? Choose a prebuilt theme name, or “custom” for a custom theme: (Use arrow keys) – Indigo/Pink
3. ? Set up global Angular Material typography styles? (y/N) – Yes
4. ? Include the Angular animations module? (Use arrow keys) – Include and enable animations

ng add @angular/material

Getting started with Angular Material Dialog Component

We are going to use the Angular Material Dialog Component for creating a modal component. For that, let’s import the DialogModule to our AppModule.

// app.module.ts
import { MatDialogModule } from '@angular/material/dialog';

@NgModule({
  imports: [
    ...,
    MatDialogModule,
  ],
  ...
})
export class AppModule { }

Now that the import is done and the module is available, we can go ahead with the implementation. We will create a confirmation modal with a yes/no button, and log the user’s selection, when any of the button is clicked.

ng generate component components/confirmation-modal
// or in short
// ng g c components/confirmation-modal
// the components/ directs in which folder to create the component in, and this is relative to the app/ folder

This will create a ConfirmationModal component inside our app/components folder.

// confirmation-modal.component.ts
import { Component, Inject, OnInit } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';

@Component({
  templateUrl: './confirmation-modal.component.html',
})
export class ConfirmationModalComponent implements OnInit {
  name = '';
  constructor(
    public dialogRef: MatDialogRef<ConfirmationModalComponent>,
    @Inject(MAT_DIALOG_DATA) public data: string,
  ) { }
  ngOnInit(): void {
    this.name = this.data;
  }
  onNoClick() {
    this.dialogRef.close();
  }
}
// confirmation-modal.component.html
<h1 mat-dialog-title>Dialog Title</h1>
<div mat-dialog-content>
  <mat-form-field class="example-full-width" appearance="fill">
    <mat-label>My name is</mat-label>
    <input matInput placeholder="your name" [(ngModel)]="name">
  </mat-form-field>
</div>
<div mat-dialog-actions>
  <button mat-raised-button (click)="onNoClick()">No</button>
  <button mat-raised-button color="primary" cdkFocusInitial [mat-dialog-close]="name">Save</button>
</div>

This is the simplest code to get the modal up, with the required bells and whistles.

Now we can use this Modal in the AppComponent.
Let’s consider we have a button, and on it’s click, we fire a function named openModal(), which will open the Modal component.

// app.component.ts
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
export class AppComponent {
  dialogRef: MatDialogRef<any, any> | undefined;

  constructor(private dialog: MatDialog) {}

  openModal() {
    this.dialogRef = this.dialog.open(ConfirmationModalComponent, {
      // height: '400px', width: '600px', // there are additional configurations too
      data: 'Sam'
    });
    this.dialogRef.afterClosed().subscribe((response: string) => {
      console.log('closed', response);
    });
  }
}

This minimum amount of code is enough to open a Modal and the output is as below:

dialog example

More on this can be found here. Happy Coding!

Leave a Reply