How to showcase a basic alert dialog using Material Angular

I'm currently utilizing Material Angular (found on Angular Material). However, I have noticed that the examples provided on the website appear to be overly complex. Additionally, most tutorials available online are either outdated or they focus on using AngularJS instead of the latest version. Is there a simple way for me to display a basic alert similar to Android's AlertDialog? This alert should include a title, a message, and options for confirming or canceling.

Answer №1

UPDATE:

A convenient way to handle dialogs in your Angular component is by using a template reference in the HTML file and passing it to the MatDialog#open method in the TypeScript file.

Another approach is to access the template reference in the component view and pass it to a custom method that accepts the reference.

To better understand, refer to the code snippet below where two dialog examples are demonstrated:

(Assuming the following project structure)

app/
  app.component.html
  app.component.ts

app.component.html:

<button mat-button (click)="openDialogWithRef(firstDialog)">Open dialog with reference</button>
<button mat-button (click)="openOtherDialog()">Open dialog programmatically</button>

<ng-template #firstDialog>
  <h2 matDialogTitle>Hello, world!</h2>
  <p matDialogContent><em>Content for this dialog goes here...</em></p>
  <mat-dialog-actions align="end">
    <button mat-button matDialogClose>Dismiss</button>
  </mat-dialog-actions>
</ng-template>

<ng-template #secondDialog>
  <h2 matDialogTitle>Hello, second dialog!</h2>
  <p matDialogContent>This template reference was accessed using <code>@ViewChild</code>, allowing querying of components/template references in the component view.</p>
  <mat-dialog-actions align="end">
    <button mat-button matDialogClose>Dismiss</button>
  </mat-dialog-actions>

app.component.ts (condensed):

import { ViewChild, TemplateRef } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';

// ...
export class AppComponent {
  @ViewChild('secondDialog') secondDialog: TemplateRef<any>;

  constructor(private dialog: MatDialog) { }

  openDialogWithRef(ref: TemplateRef<any>) {
    this.dialog.open(ref);
  }

  openOtherDialog() {
    this.dialog.open(this.secondDialog);
  }
}

This streamlined method eliminates the need for creating new components solely for dialogs, as well as declaring them in the entryComponents section of your module.

However, managing multiple dialog templates within a single component view may become cumbersome.


Original solution

For your specific requirement, consider the example provided below:

(Assuming the directory structure as detailed)

app/
  my-alert-dialog/
    my-alert-dialog.component.html
    my-alert-dialog.component.ts
  app.component.ts
  app.module.ts

my-alert-dialog.component.html

<h2 matDialogTitle>Unregister?</h2>
<mat-dialog-content>
  <p>Upon unregistering, all stored data will be deleted. Confirm action?</p>
</mat-dialog-content>
<mat-dialog-actions align="end">
  <!--
    Note that any content can be passed to `matDialogClose` including objects or arrays.
    Ensure to bind them using property binding like so [matDialogClose]="{'status': 'confirm'}"
  -->
  <button mat-button matDialogClose="cancel" color="primary">Cancel</button>
  <button mat-button matDialogClose="confirm" color="warn">Unregister</button>
</mat-dialog-actions>

Detailed explanation of the above code:

  • [matDialogTitle] / [mat-dialog-title]: Directive used typically on an h2 element to specify the dialog's title.
  • [matDialogContent] / [mat-dialog-content] / mat-dialog-content: Directive denoting the content of the dialog.
  • [matDialogActions] / [mat-dialog-actions] / mat-dialog-actions: Directive indicating the dialog's actions.
  • [matDialogClose] / [mat-dialog-close]: Directive often applied on a button element to close the dialog when clicked. It can include a parameter (of type any) which is then passed back to the dialog opener.

my-alert-dialog.component.ts

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

@Component({
  selector: 'app-alert-dialog', // Customize as needed
  templateUrl: './my-alert-dialog.component.html'
})
export class MyAlertDialogComponent { }

app.component.ts (excerpt)

import { MatDialog } from '@angular/material';
import { MyAlertDialogComponent } from './my-alert-dialog/my-alert-dialog.component';
// ...
export class AppComponent {
  constructor(private dialog: MatDialog) { }
  unregister() {
    let dialogRef = this.dialog.open(MyAlertDialogComponent);
    dialogRef.afterClosed().subscribe(result => {
      if (result == 'confirm') {
        console.log('Unregistered');
      }
    })
  }
}

app.module.ts (excerpt)

import { MatDialogModule } from '@angular/material';
import { MyAlertDialogComponent } from './my-alert-dialog/my-alert-dialog.component';

@NgModule({
  declarations: [
    // ...
    MyAlertDialogComponent
  ],
  imports: [
    // ...
    MatDialogModule
  ],
  entryComponents: [
    // Additional information at https://material.angular.io/components/dialog/overview#configuring-dialog-content-via-code-entrycomponents-code-
    MyAlertDialogComponent
  ]
})
export class AppModule { }

Live Demo

Answer №2

Recently, I implemented a Sweet Alert in my Angular project. If you're interested, you can check out the tutorial that helped me at .

This method is incredibly simple and efficient for creating alerts within an Angular application.

$ npm install --save sweetalert2

To start using Sweet Alert, add import Swal from 'sweetalert2'; to your TypeScript file and then create an alert with

Swal.fire('This is a simple and pleasant alert')
.

Answer №3

To set up, execute the command npm i @angular/material, then create a new dialog component named EmployeeDialog.

If you wish to include a table and a close button in the dialog, follow these instructions.

In your EmployeeDialog.html file, add the following code:

<div md-dialog-content>
<!-- Close button for the dialog -->
<button class="close" mat-button (click)="onNoClick()">
 <mat-icon>close</mat-icon>   
</button>   
<div>   
 <table>
   <th>Id</th><th>Name</th>Addess<th></th><
   <tr *ngFor="let emp of emplyee; let i = index" border="1">
     <td>{{emp.DeviceID}}</td>
     <td>{{emp.FriendlyName}}</td>
   </tr>
 </table>   
</div>   
</div>

Your EmployeeDialog.ts file should contain the following code:

import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
export class EmployeeDialog implements OnInit {

  constructor(public dialogRef: MatDialogRef<EmployeeDialog>, @Inject(MAT_DIALOG_DATA) public data: any){ }
  
  //write code to handle close
  }
}

To open the EmployeeDialog from the SourceComponent, call the Employeelist() function as shown below:

SourceComponent.ts file

public Employeelist()
{
    const dialogRef = this.dialog.open(EmployeeDialog, {
    width: '80%',
    height:'80%',
    panelClass: 'my-dialog',
    disableClose: true ,
    data: employeeList
  });
}

Add the following code to your app.module.ts file:

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

import { MatDialogModule } from '@angular/material/dialog';
import { MatButtonModule } from '@angular/material/button';

@NgModule({
  declarations: [
    AppComponent,
    EmployeeDialog,
    SourceComponent,
  ],
  imports: [
    MatDialogModule,
    MatButtonModule,
    BrowserModule,
  ],
  entryComponents: [EmployeeDialog],
  bootstrap: [ AppComponent ],
  providers: []
})
export class AppModule { }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is data binding not functioning properly in Angular 8?

This query has been raised multiple times in the past and I have reviewed all the suggested solutions. However, I am encountering a common issue - how to retrieve data from the parent component to the child component. I'm unsure of where I'm goin ...

Parsing temporary storage of database query results

My experience with OOP languages like C# and Java has been good, but I am relatively new to JavaScript/TypeScript. I find callback functions confusing, especially when using them with the BaaS ParseDB. For example, finding all playlists for a certain user ...

Adjusting the selection in the Dropdown Box

I've been attempting to assign a value to the select box as shown below: <dx-select-box [items]="reportingProject" id="ReportingProj" [text]="reportingProject" [readOnly]="true" > ...

Obtaining the initial successful value within an array containing TaskEithers

As someone who is diving into functional programming and just beginning to explore fp-ts, I am grappling with understanding the util functions provided. My current challenge involves figuring out how to handle TaskEithers as fallbacks within an array. I h ...

Tips for effectively utilizing the Angular 14 inject function while setting multi to true

I have a service with multiple instances that I provide in multiples. { provide: MyAbstractService, useClass: MyServiceA, multi: true }, { provide: MyAbstractService, useClass: MyServiceB, multi: true }, For reasons I prefer not to disclose, I am look ...

What is the best way to distribute a Typescript module across multiple projects without having to duplicate it each time?

I currently have two folders named shared and project1 within a larger folder called node. I am in the process of working on multiple Node projects that are independent and are all located within the node folder. Within the shared folder, there is an inde ...

Converting a string into a Date in Typescript while disregarding the timezone

Upon receiving a date in string format like this (e.g.): "11/10/2015 10:00:00" It's important to note that this is in UTC time. However, when creating a Date object from this string, it defaults to local time: let time = "11/10/2015 10:00:00"; let ...

Encountered a problem while integrating Flickity Events with Vue3 and TypeScript: receiving an error stating that "this$refs.flickity.on

I have successfully implemented a custom Flickity.vue object for Vue 3 with TypeScript support, based on the solution provided here. However, when attempting to listen for events on my flickity carousel, I encounter runtime type errors in the console: thi ...

Utilize a Typescript library within a separate Typescript library

I have a TypeScript library on GitHub that I want to install using npm install --save git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5f38362b1d15c3f4">[email protected]</a>:User/mylib.git into my targ ...

The Nestjs ClientMqtt now has the capability to publish both pattern and data to the broker, as opposed to just sending

I am currently utilizing Nestjs for sending data to a Mqtt Broker. However, I am facing an issue where it sends both the pattern and data instead of just the data in this format: { "pattern": "test/test", "data": " ...

Numerous Angular projects nestled neatly within one single overarching project

As my angular project continues to grow, the number of files is increasing and the overall size of the project is expanding I am considering breaking the project into multiple parts. I am thinking of implementing a microservice architecture For instance ...

Angular 5 does not recognize the function submitEl.triggerEventHandler, resulting in an error

Greetings! I am currently working on writing unit test cases in Angular5 Jasmine related to submitting a form. Below is the structure of my form: <form *ngIf="formResetToggle" class="form-horizontal" name="scopesEditorForm" #f="ngForm" novalidate (ngSu ...

What is the best way to incorporate TypeScript variables into CSS files?

In my Angular project, I am aiming to utilize a string defined in Typescript within a CSS file. Specifically, I want to set the background image of a navbar component using a path retrieved from a database service. Although I came across suggestions to use ...

Attempting to implement ngModel in Angular for an HTML element

I am attempting to do the following: <div class = "form-group"> <label for="funktion">Funktion</label> <select formControlName="funktion" id="funktion" class="form-control" ngModel #Funktion="ngModel" required > <opt ...

Issue with running Angular Application through docker-compose.yml file is stopping the execution

Below is the docker file I have created for my angular application: Dockerfile: # base image FROM node:10.16.0-alpine AS build-step # set working directory WORKDIR /app COPY package.json ./ RUN npm install COPY . . RUN npm run build FROM nginx:1.16.1-alp ...

Pausing until all RxJS calls are completed before moving on to the next block of code

I have a scenario where I am iterating over a list of streets and making API calls for each street. I am storing the responses in an Object Array and want to execute the next code block only after all the requests are finished. However, I am facing an issu ...

Blend a standard `Record` with a fixed entity

When given the type, export type ValidationErrors<T extends string> = Partial<Record<T, string>> & { errorsCount: number }; You have the ability to create an object in this manner: const errors: ValidationErrors<'hello' ...

VS code shines a spotlight on Jasmine functions within Angular 6

Recently, I made the switch to Angular 6.0. However, in VS Code, all jasmine functions are being highlighted as unknown even though they work fine and the tests run successfully. How can I make intellisense recognize Jasmine? In previous versions, a worka ...

The transition() function in Angular 2.1.0 is malfunctioning

I am struggling to implement animations in my Angular 2 application. I attempted to use an example I found online and did some research, but unfortunately, I have not been successful. Can anyone please assist me? import {Component, trigger, state, anima ...

Getting node siblings within an Angular Material nested tree: A comprehensive guide

Struggling to retrieve the list of sibling nodes for a specific Angular Material tree node within a nested tree structure. After exploring the Angular Material official documentation, particularly experimenting with the "Tree with nested nodes," I found t ...