Create Your Custom Modal With Angular Material

Braulio
2 min readMay 16, 2021
Custom Angular Material

Angular Material provides a really helpful components ready to use in your Angular project, most of them has amazing features which can be implemented by some input settings and custom CSS.

But what happens if you want to create your custom components to have more control over them with out losing the default Material Behavior? For example the modal component included in the Angular Material library works fine but we can’t customize advanced behavior or editing the CSS easily. In this example I’m going to show you specifically how to create your own modal service so you will have full customizable control over it.

Required Libraries

You will need to have an angular project with the angular material and angular CDK libraries installed:

npm install --save @angular/material @angular/cdk

Code

The entire example will be done only in one files which shall include our main custom service for opening a modal. Since we are going to use the angular CDK functionality, we need to import the required services for using the overlay and the portal from CDK.

Create the file my-custom-modal.service.ts and put the content below:

import { Overlay, OverlayConfig, OverlayRef } from '@angular/cdk/overlay';import { ComponentPortal, ComponentType, PortalInjector } from '@angular/cdk/portal';

Then define the custom interface for the modal configuration and the default values for it.

interface MyOverlayConfig {
panelClass?: string
hasBackdrop?: boolean
backdropClass?: string
disableClose?: boolean
data?: any
height?: string | number
width?: string | number
}
const DEFAULT_CONFIG: MyOverlayConfig = {
hasBackdrop: true,
backdropClass: 'my-coupons-overlay-backdrop',
panelClass: 'my-coupons-overlay-panel'
}
export const MY_OVERLAY_DATA = new InjectionToken<any ('MY_OVERLAY_DATA');

We will need a custom class for the overlay ref:

export class MyOverlayRef {  afterClosed = new Subject<any>();  backdropClick = new Subject<any>();  constructor(private overlayRef: OverlayRef) { }  close(data?: any): void {
this.overlayRef.dispose();
this.afterClosed.next(data);
this.afterClosed.complete();
}
}

Finally, the main service class will contain all needed methods for creating the overlay and opening our custom modal. The entire file content:

Testing Our Custom Modal

Now we only need to include our new created service in any component of our project and call the open(...) method with the desired component to open within the modal.

Well done! Now you can open any component content inside an Angular Material modal and having full control over it.

--

--