Rijul Dahiya
·Follow
2 min read·Apr 23, 2023--
In this tutorial, we’ll show you how to create a pop-up modal in an Angular application using Angular Material, and include a form field for entering a “query name” value. The modal will use reactive forms and validation to ensure that the “query name” field is not empty.
Step 1: Importing Necessary Modules To start, we need to import the necessary modules in our component. We’ll need the following:
import { Component } from '@angular/core';import { MatDialogRef } from '@angular/material/dialog';The MatDialog and MatDialogRef modules are needed to create the pop-up modal, and the FormBuilder and FormGroup modules are needed to create the reactive form.
Step 2: Defining the Component Class Next, we’ll define our component class and inject the MatDialog and FormBuilder services.
@Component({ selector: 'app-query-modal', template: `Enter Query Name Cancel Save `})export class QueryModalComponent {constructor(private dialogRef: MatDialogRef ) { }
onSubmit(queryName: string) {this.dialogRef.close(queryName); }}
In the QueryModalComponent, we create a reactive form using the FormBuilder module, and include a validation rule to make the "query name" field required. We also include an error message that will be displayed if the field is empty. In the onSubmit() method, we close the dialog and pass the entered "query name" value back to the parent component.
Step 3: Opening the Modal and Returning the Value In our parent component, we create a method that will open the modal and return the entered “query name” value as a promise.
async openQueryModal(): Promise { const dialogRef = this.dialog.open(QueryModalComponent, {width: '400px' });const result = await dialogRef.afterClosed().toPromise();
return result;}
The openQueryModal() method opens the QueryModalComponent in a dialog and sets the width of the dialog to 400 pixels. We then use the afterClosed() method to wait for the dialog to be closed, and return the entered "query name" value as a promise.
Step 4: Using the Modal to Get the Query Name Finally, we can use the openQueryModal() method to get the entered "query name" value from the user and do something with it.
async saveQuery() { const queryName = await this.openQueryModal(); console.log('Entered query name:', queryName); // Do something with the entered query name}Note that you will also need to add the MatDialogModule and FormsModule to your app module imports in order for this code to work properly.