Angular Material Dialog in Same Component with ng-template

By Arvind Rai, November 09, 2022
On this page we will learn to create Material Dialog using ng-template.
1. The MatDialog service is used to open Material Design modal dialogs.
2. A Dialog can be created either by creating a component or by using <ng-template> in dialog opener component.
3. To create Dialog, we need to import following module in our application module.
import { MatDialogModule } from '@angular/material/dialog'; 
Now let us discuss creating Dialog using ng-template in detail.

Technologies Used

Find the technologies being used in our example.
1. Angular 13.1.0
2. Angular Material 13.3.9
3. Node.js 12.20.0
4. NPM 8.2.0

Creating Dialog with <ng-template>

Find the HTML template code to create dialog with <ng-template> .
<ng-template let-data #myCityDialog>
  <h2 mat-dialog-title> Heading  </h2>
  <div mat-dialog-content> Content  </div>
  <div mat-dialog-actions> 
     <button mat-button mat-dialog-close>Close</button>
  </div>
</ng-template> 
mat-dialog-title : Applied to h1, h2 for heading.
mat-dialog-content : Scrollable content for dialog.
mat-dialog-actions : Container for action buttons at the bottom of the dialog.
mat-dialog-close : Used with <button>. It makes the button close the dialog with an optional result from the bound value.

Now look into the line of code.
<ng-template let-data #myCityDialog> 
data : Contains data sent by dialog opener component.
myCityDialog : Template reference used to access template by @ViewChild decorator.

To open dialog, we can create a button in same HTML template.
<button mat-raised-button (click)="openCityDialog()">Pick user</button> 

Open Dialog

1. Create TemplateRef instance using @ViewChild decorator.
@ViewChild('myCityDialog') cityDialog = {} as TemplateRef<User>; 
2. To open dialog, we need to call open method of MatDialog service.
MatDialog.open 
Parameters:
arg1 : ComponentType<T> | TemplateRef<T>
arg2?: MatDialogConfig<D>
Returns:
MatDialogRef<T, R>

Find the code snippet of TypeScript file.
constructor(public dialog: MatDialog) { }

openCityDialog() {
 this.dialogRef = this.dialog.open(this.cityDialog,
  { data: this.user, height: '350px', width: '250px' });

  this.dialogRef.afterClosed().subscribe((result: User) => {
    console.log('The City dialog was closed.');
    console.log(result?.name + ' - ' + result?.city);
  });
} 
3. The input data to Dialog is obtained by subscribing observable returned by afterClosed method.
4. To close Dialog, use MatDialogRef.close() method.
onCancelCityDialog() {
  this.dialogRef.close();
} 

Complete Example

In our example, we are creating two dialogs using ng-template. One dialog is taking input from user and sending it back to opener. Second dialog is just displaying message.
example-dialog.component.html
<h2>Dialog Demo</h2>
<p>
  <button mat-raised-button (click)="openCityDialog()">Pick user</button>
  <br /> {{user.name}}
  <br /> {{user.city}}
</p>
<p>
  <button mat-raised-button (click)="openInfoDialog()">Info</button>
</p>

<ng-template let-data #myCityDialog>
  <h2 mat-dialog-title>User Detail</h2>
  <div mat-dialog-content>
    <p>Name:
      <mat-form-field appearance="fill">
        <input matInput [(ngModel)]="data.name" placeholder="Enter name">
      </mat-form-field>
    </p>
    <p>City:
      <mat-form-field appearance="fill">
        <input matInput [(ngModel)]="data.city" placeholder="Enter city">
      </mat-form-field>
    </p>
  </div>
  <div mat-dialog-actions>
    <button mat-button (click)="onCancelCityDialog()">Cancel</button>
    <button mat-button [mat-dialog-close]="data" cdkFocusInitial>Ok</button>
  </div>
</ng-template>

<ng-template let-data #myInfoDialog>
  <h2 mat-dialog-title>Information</h2>
  <div mat-dialog-content>
    {{data}}
  </div>
  <div mat-dialog-actions>
    <button mat-button mat-dialog-close>Close</button>
  </div>
</ng-template> 
example-dialog.component.ts
import { Component, TemplateRef, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { User } from './user';

@Component({
  selector: 'example-dialog',
  templateUrl: './example-dialog.component.html',
})
export class ExampleDialogComponent {
  user = { name: '', city: '' };
  dialogRef: any;

  @ViewChild('myCityDialog') cityDialog = {} as TemplateRef<User>;
  @ViewChild('myInfoDialog') infoDialog = {} as TemplateRef<string>;

  constructor(public dialog: MatDialog) { }

  openCityDialog() {
    this.dialogRef = this.dialog.open(this.cityDialog,
      { data: this.user, height: '350px', width: '250px' });

    this.dialogRef.afterClosed().subscribe((result: User) => {
      console.log('The City dialog was closed.');
      console.log(result?.name + ' - ' + result?.city);
    });
  }
  onCancelCityDialog() {
    this.dialogRef.close();
  }

  myInfo = "Namaste to the world!";
  openInfoDialog() {
    this.dialogRef = this.dialog.open(this.infoDialog,
      { data: this.myInfo, height: '200px', width: '250px' });

    this.dialogRef.afterClosed().subscribe(() => {
      console.log('The Info dialog was closed.');
    });
  }
} 
user.ts
export interface User {
    name: string;
    city: string;
} 
app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `<example-dialog></example-dialog>`
})
export class AppComponent {
} 
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatDialogModule } from '@angular/material/dialog';

import { AppComponent } from './app.component';
import { ExampleDialogComponent } from './example-dialog.component';

@NgModule({
  declarations: [
    AppComponent,
    ExampleDialogComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    ReactiveFormsModule,
    MatFormFieldModule,
    MatButtonModule,
    MatInputModule,
    MatDialogModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { } 

Run Application

To run the application, find the steps.
1. Install Angular CLI using link.
2. Install Angular Material using link.
3. Download source code using download link given below on this page.
4. Use downloaded src in your Angular CLI application.
5. Run ng serve using command prompt.
6. Access the URL http://localhost:4200
Find the print screen of the output.
Angular Material Dialog in Same Component with ng-template

Reference

Angular Material Dialog

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI











©2022 concretepage.com | Privacy Policy | Contact Us