AppDividend
Latest Code Tutorials

Angular Modal Tutorial With Example | Angular Material Dialog

2

Angular Modal Tutorial With Example is today’s topic. We will use Angular Material for this demo. We use Angular 7 for this example. Angular Material is the ground running with significant, modern UI components that work across the web, mobile, and desktop applications. Angular Material components will help us to construct attractive UI and UX, consistent, and functional web pages and web applications while keeping the modern web design principles like browser portability and compatibility. For this tutorial, I have used the angular material dialog‘s same example, but I have shown step by step from scratch.

Angular Modal Tutorial With Example

The first step is to Install an Angular 7 project.

Step 1: Create an Angular Project

Type the following command.

ng new angularmodal

 

Angular Material Modal

Step 2: Install Angular Material Libraries.

Go inside the project folder and install the hammerjs using the following command.

npm install --save hammerjs

Hammer.js is an optional dependency and helps with touch support for the few of the components.

Now, install Angular Material and Angular Animations using the following command.

npm install --save @angular/material @angular/animations @angular/cdk

Now, include hammerjs inside an angular.json file. You can find this file on the root of the angular project.

Step 3: Create the Custom Material Module File.

Okay, now inside src >> app folder, create one module file called material.module.ts. We have created this material.module.ts file separately because, in future, we can import the different Material components in this file and this file we will import inside the app.module.ts file.

Write the following code inside the material.module.ts file.

// material.module.ts

import { NgModule } from '@angular/core';

import { MatDialogModule, MatFormFieldModule, MatButtonModule, MatInputModule } from '@angular/material';
import { FormsModule } from '@angular/forms';

@NgModule({
  exports: [FormsModule, MatDialogModule, MatFormFieldModule, MatButtonModule, MatInputModule]
})
export class MaterialModule {}

Here, we have imported the only FormsModule from Angular FormsMatDialogModule, MatFormFieldModule, MatInputModule, and MatButtonModule components from the Angular Material Library.

Step 4: Import a pre-built theme and Material icons

Angular Material comes with some pre-built themes. These themes provide us set off the colors and basic styling. The main available themes are these: indigo-pinkdeeppurple-amberpurple-green and pink-bluegrey. To import the theme in our project, we can add the following code to your global styles.css file. The file is inside the src folder.

@import '~@angular/material/prebuilt-themes/indigo-pink.css';

You can also have access to the Material Design icons and use these named icons with the <mat-icon> component. To import them to your project, you can add this to the head section of your project’s root index.html file.

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

Now the final step is to import material.module.ts and other angular material module and BrowserAnimationsModule files inside the app.module.ts file.

// app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material.module';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, BrowserAnimationsModule, MaterialModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Step 5: Angular Material Modal Implementation.

The MatDialog service can be used to open modal dialogs with Material Design styling and animations.

Now, create inside the app.component.ts file, write the following code.

// app.component.ts

import { Component, Inject } from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material';
import { DialogData } from './DialogData';

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

}

Also, create an interface called DialogData.ts file inside the src >> app folder. Write the following code inside that file.

// DialogData.ts

export interface DialogData {
  animal: string;
  name: string;
}

Now, create an Angular Component by typing the following command.

ng g c modal --module app --spec=false

It will create a modal-component folder inside the app folder.

Write the following code inside the modal.component.ts file.

// modal.component.ts

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

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.css']
})
export class ModalComponent implements OnInit {

  constructor(
    public dialogRef: MatDialogRef<ModalComponent>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData) {}

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

  ngOnInit() {
  }

}

ModalComponent.ts class is the actual class that implements the Angular Material Modal.

ModalComponent class accepts the DialogData and display inside the dialog. We have used the Dependency Injection to inject the data inside the Angular Dialog.

Write the HTML file of ModalComponent inside the modal.component.html file.

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

In this HTML file, we have used the Material Modules and Angular Form modules which we have imported earlier inside the material.module.ts file.

Above HTML will be shown, when a user clicks on the button that pops up the Modal.

Now, write the following code inside the app.component.ts file.

// app.component.ts

import { Component, Inject } from '@angular/core';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { ModalComponent } from './modal/modal.component';

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

  constructor(public dialog: MatDialog) {}

  openDialog(): void {
    const dialogRef = this.dialog.open(ModalComponent, {
      width: '250px',
      data: {name: this.name, animal: this.animal}
    });

    dialogRef.afterClosed().subscribe(result => {
      this.animal = result;
    });
  }
}

First, we have imported the ModalComponent inside the app.component.ts file.

Then we have created one function called openDialog() which will open the ModalComponent.

We have passed the data like name and animal to that ModalComponent.

When the user closes the ModalComponent, AppComponent gets the value of animal which we have typed inside the ModalComponent and display inside the AppComponent file.

Write the following code inside the app.component.html file.

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

Here, you can see that we have passed the data between AppComponent and ModalComponent. The data is name and animal.

If the user has typed the animal name inside the ModalComponent, then after the closing of Modal, we can see the animal name inside the AppComponent.

Still, there is one thing missing which is the entryComponents of the Angular application which we need to define inside the app.module.ts file. So, our final app.component.ts file looks like below.

// app.component.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MaterialModule } from './material.module';

import { AppComponent } from './app.component';
import { ModalComponent } from './modal/modal.component';

@NgModule({
  declarations: [AppComponent, ModalComponent],
  imports: [BrowserModule, BrowserAnimationsModule, MaterialModule],
  providers: [],
  bootstrap: [AppComponent],
  entryComponents: [ModalComponent]
})
export class AppModule {}

Finally, save the file and start the angular dev server by the following command.

ng serve --open

It will open the browser, and you can see something like below.

 

Angular Material Modal Implementation.

Now, first, type your name and click the button pick one and you will see the Angular Material Dialog.

 

Angular Modal Tutorial With Example | Angular Material Dialog

Now, if you press the Ok and if you have typed the animal name then you will see something like below.

 

Angular Modal Tutorial With Example

So, we have successfully implemented the Angular Material Modal or Angular Modal or Angular Material Dialog. You can find more details about the Angular Material Dialog here.

Finally, Angular Modal Tutorial With Example | Angular Material Dialog is over.

Github Code

2 Comments
  1. Kishore kumar says

    Hi, can you help me how to do the customized css for the angular material in the designing.

  2. Aravind says

    Thank you so much

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.