Build Modal / Dialog in Angular 16 with Angular Material

Last Updated on by in Angular Material
In this tutorial, we are going to go through abut Angular 16 Modal with Angular Material Dialog component.To create a Modal box in Angular web application, we use Angular Material 10 UI library. Angular material UI library offers a wide range of UI components to create real-world web and mobile apps.

Angular Material UI components help us to build robust, consistent, engaging, and user-centric interfaces. Here, we are going to highlight the most common use cases related to Angular 8 Modals.

For the demo purpose, I have taken the help of Angular material dialog component to create an Angular Modal box.

Let us start creating an Angular Modal step by step by following this tutorial.

Angular Material Modal or Dialog Example

  • Closing The Angular material Dialog
  • Configuration of Angular Material Dialog options
  • Passing & Receiving the Data in the Angular Model
  • Implementing Angular Material Dialog in an Angular app
  • Creating an Angular Modal using Angular Material dialog
  • Installation and Configuration of Angular Material project

Install Angular App

Let’s install the Angular project to show the Angular Modal demo with Angular Material Dialog.

ng new angular-material-dialog

# ? Would you like to add Angular routing? Yes
# ? Which stylesheet format would you like to use? SCSS

Go inside project folder.

cd angular-material-dialog

Remove Angular TypeScript Errors

Set following properties to false in tsconfig.json file:

"compilerOptions": {
 ...
 ...
   "strict": false,
   "noPropertyAccessFromIndexSignature": false,
 ...
 ...
},
  "angularCompilerOptions": {
    "strictTemplates": false
  }

Configure Angular Material Library

Use the following command to install and configure Material library in Angular Modal project:

ng add @angular/material

In the next step, we are going to have a look at Angular Material pre-built themes.

Angular Material offers following pre-built themes deeppurple-amber, indigo-pink, purple-green and pink-bluegrey.

To set up any of the given pre-built Material theme, we have to choose among the given options and Angular CLI will automatically ad the theme in your styles.scss file.

Choose Angular Material Pre-built Theme from the following options:

? Choose a prebuilt theme name, or "custom" for a custom theme: Indigo/Pink

❯ Indigo/Pink        [ Preview: https://material.angular.io?theme=indigo-pink ] 
  Deep Purple/Amber  [ Preview: https://material.angular.io?theme=deeppurple-amber ] 
  Pink/Blue Grey     [ Preview: https://material.angular.io?theme=pink-bluegrey ] 
  Purple/Green       [ Preview: https://material.angular.io?theme=purple-green ]
# ? Set up global Angular Material typography styles? Yes
# ? Set up browser animations for Angular Material? Yes

Check out the full Angular Material documentation here.

Create Custom Angular Material Module File

Now, we are going to create a custom angular-material.module.ts file, in this file we will import the following Angular material ui components from the Angular Material library.

  • MatDialogModule
  • MatFormFieldModule
  • MatInputModule
  • MatButtonModule

Go to angular-material.module.ts file and add the following code.

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { MatButtonModule } from '@angular/material/button';
import { MatIconModule } from '@angular/material/icon';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import {MatDialogModule} from '@angular/material/dialog';


const materialModules = [
  MatButtonModule,
  MatIconModule,
  MatFormFieldModule,
  MatInputModule,
  MatDialogModule
];

@NgModule({
  imports: [
    CommonModule,
    ...materialModules
  ],
  exports: [
    ...materialModules
  ],
})

export class AngularMaterialModule { }

Integrating Angular Modal using Angular Material Dialog

Now, we are going to generate my-modal component, using the following command.

ng g c my-modal --module app

Add the given below code in the my-modal.component.ts file.

import { Component, OnInit, Inject } from '@angular/core';
import {
  MatDialogRef,
  MatDialogModule,
  MAT_DIALOG_DATA,
} from '@angular/material/dialog';

export interface ModalData {
  name: string;
  color: string;
}

@Component({
  selector: 'app-my-modal',
  templateUrl: './my-modal.component.html',
  styleUrls: ['./my-modal.component.scss'],
})
export class MyModalComponent implements OnInit {
  constructor(
    public dialogRef: MatDialogRef<MyModalComponent>,
    @Inject(MAT_DIALOG_DATA) public data: ModalData
  ) {}

  onNoClick(): void {
    this.dialogRef.close();
  }

  ngOnInit() {}
}

Go to my-modal.component.html file and add the following code in it.

<h1 mat-dialog-title>Hi {{data.name}}</h1>
<div mat-dialog-content>
  <p>What's your favorite color?</p>
  <mat-form-field>
    <input matInput [(ngModel)]="data.color">
  </mat-form-field>
</div>
<div mat-dialog-actions>
  <button mat-button (click)="onNoClick()">No Thanks</button>
  <button mat-button [mat-dialog-close]="data.color" cdkFocusInitial>Ok</button>
</div>

Then, in this step we are going to inject MyModalComponent inside the entryComponents array in the app module file. This is also

Here is the final version of our app.module.ts file, kindly compare it with your code.

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AngularMaterialModule } from './angular-material.module';
import { MyModalComponent } from './my-modal/my-modal.component';

@NgModule({
  declarations: [AppComponent, MyModalComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    AngularMaterialModule,
    FormsModule,
    ReactiveFormsModule,
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
})

export class AppModule {}

In this step, we are going to use MatDialog service, and this service helps to open the Angular Modal with Material dialogs.

Now, head over to app.component.ts file, add the following code.

import { Component } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { MyModalComponent } from './my-modal/my-modal.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  name: string;
  color: string;

  constructor(public dialog: MatDialog) {}

  openDialog(): void {
    const dialogRef = this.dialog.open(MyModalComponent, {
      width: '400px',
      data: { name: this.name, color: this.color },
    });

    dialogRef.afterClosed().subscribe((res) => {
      this.color = res;
    });
  }
}

As you can see the MatDialogRef Angular Material service provides an option to close the opened Angular Modal box.

Finally, go to app.component.html file, include the given below code.

<div>
  <mat-form-field>
    <input
      matInput
      [(ngModel)]="name"
      placeholder="What's your favorite color?"
    />
  </mat-form-field>
</div>
<div>
  <button mat-raised-button (click)="openDialog()">Pick one</button>
</div>
<h4 *ngIf="color">
  You selected:
  <p style="font-weight: bold">{{ color }}</p>
</h4>

Conclusion

Angular Material is a popular UI component library for Angular applications developed by the Angular team.

It provides a set of pre-built and customizable components to build modern, responsive, and visually appealing user interfaces.

In this guide, we learned to use one of the important components provided by Angular Material is the “MatTabs” component, which helped us to create tab-based navigation.

Finally, we have shown you how to create an overlay Modal box in Angular using Angular Material Dialog UI component service.

I hope this tutorial has helped you learn the Angular Material Modal concept.

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.