DEV Community 👩‍💻👨‍💻

John Peters
John Peters

Posted on • Updated on

Material Dialog in 10 minutes

A Minimal example to get started with Material Dialog using Angular.

 import { MatDialog, MatDialogConfig } from "@angular/material/dialog";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"],
})
export class AppComponent {
  constructor( private dialog: MatDialog) {}
 // The HTML button click handler
 onButtonClicked($event) {
    let httpClient: HttpClient = new HttpClient(this.httpHandler);
// Causes a CORS error 
httpClient.get("http://www.google.com").subscribe(
      (response) => {
        console.log(response);
      },
      (error) => {
        let dc = new MatDialogConfig();
        dc.autoFocus = true;
        // Important part
        dc.data = error;
        this.dialog.open(ErrorHandlerComponent, dc);
      }
    );
  }

Enter fullscreen mode Exit fullscreen mode

This statement is the call to open but uses the injected component as the display.

this.dialog.open(ErrorHandlerComponent, dc);
Enter fullscreen mode Exit fullscreen mode

The Injected Component

export class ErrorHandlerComponent implements OnInit, AfterViewInit {
  error: HttpErrorResponse;
  constructor(
    // Must inject MAT_DIALOG_DATA
    @Inject(MAT_DIALOG_DATA) public data: any,
    private ref: ElementRef,
    private HtmlElementService: HtmlElementService
  ) {
    // Html binds to this.error
    this.error = data;
  }
Enter fullscreen mode Exit fullscreen mode

The Injected Component's HTML

<h1 mat-dialog-title>{{ error.statusText }}</h1>
<div mat-dialog-content>
  <p>Message</p>
  {{ error.message }}
</div>
<div mat-dialog-actions>
  <button class="mat-raised-button" mat-dialog-close>Close</button>
  <button class="mat-raised-button mat-primary" (click)="save()">Copy</button>
</div>
Enter fullscreen mode Exit fullscreen mode

✔️ The Result

Alt Text

Observations

Many examples show this being done in app.component, that's the only reason this example does the same.

A timer can be placed on the Injected Component to auto-close. This makes is more of an notification or toaster item.

The configuration contains many properties which are nice features.

I don't care for the data being passed in the configuration. Wouldn't this make more sense?

this.dialog.data = this.data;
let dc = new MatDialogConfig();
dc.autoFocus = true;
this.dialog.open(ErrorHandlerComponent,dc);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Hey 😍

Want to help the DEV Community feel more like a community?

Head over to the Welcome Thread and greet some new community members!

It only takes a minute of your time, and goes a long way!