Hi
I am using Angular Material dialog. I want when user clicks Cancel button it should gets closed.
Code
Employee FormThanks
Hi
I am using Angular Material dialog. I want when user clicks Cancel button it should gets closed.
Employee FormThanks
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Jaimin ShethiyaRank #177 · 13.7K reputationPosted Jun 7, 2024, 3:20 AM EDT
Hello Ramco,
user-dialog.component.html
user-dialog.component.ts
import { Component, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'; import { User } from './user'; @Component({ templateUrl: './user-dialog.component.html', }) export class UserDialogComponent { constructor( public dialogRef: MatDialogRef, @Inject(MAT_DIALOG_DATA) public data: User, ) { } onCancelUserDialog(): void { this.dialogRef.close(); } }app.module.ts
import { UserDialogComponent } from './user-dialog.component'; @NgModule({ declarations: [ AppComponent, UserDialogComponent ], providers: [ {provide: MAT_DIALOG_DEFAULT_OPTIONS, useValue: { height: '200px', width: '250px', autoFocus: true }} ],Thanks
Mayooran NavamanyRank #438 · 5.7K reputationPosted Jun 7, 2024, 12:35 PM EDT
HTML Template: Add a "Cancel" button within your form. Use Angular's
(click)event binding to call a method in your component to handle the dialog close action.Employee Form Cancel SaveComponent: Inject
MatDialogRefin the constructor of your component and define theonCancelmethod to close the dialog.import { Component } from '@angular/core'; import { MatDialogRef } from '@angular/material/dialog'; import { FormBuilder, FormGroup } from '@angular/forms'; @Component({ selector: 'app-employee-form-dialog', templateUrl: './employee-form-dialog.component.html', }) export class EmployeeFormDialogComponent { empForm: FormGroup; constructor( private fb: FormBuilder, public dialogRef: MatDialogRef ) { this.empForm = this.fb.group({ // Define your form controls here }); } onCancel(): void { this.dialogRef.close(); } Save(): void { // Handle save logic } }In this setup:
MatDialogRefservice is used to control the dialog from within the component.onCancelmethod calls theclosemethod ondialogRef, which closes the dialog.FormBuilderandFormGroup).