When faced with the task of adding a close button to multiple dialogs, I initially created wrapper components for each dialog and dynamically instantiated components inside. However, I soon realized this approach was overly complex and not very flexible. As a result, I opted to implement a directive specifically for adding the closing button to the dialogs individually. Here is how I went about it:
dialog-title.directive.ts
import {
Directive,
OnInit,
Renderer2,
ViewContainerRef,
ElementRef,
} from '@angular/core';
import { DialogCloseButtonComponent } from './dialog-close-button/dialog-close-button.component';
@Directive({
selector: `[dialogTitle]`,
standalone: true,
host: {
'[style.display]': '"flex"',
'[style.justify-content]': '"space-between"',
'[style.align-items]': '"baseline"',
'[style.padding]': '"10px 24px"',
},
})
export class DialogTitleDirective implements OnInit {
constructor(
private renderer: Renderer2,
private viewContainerRef: ViewContainerRef,
private elementRef: ElementRef,
) {}
ngOnInit() {
const closeButton = this.viewContainerRef.createComponent(DialogCloseButtonComponent);
this.renderer.appendChild(this.elementRef.nativeElement, closeButton.location.nativeElement);
}
}
dialog-close-button.component.ts
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { MatButtonModule } from '@angular/material/button';
import { MatDialogModule } from '@angular/material/dialog';
import { MatIconModule } from '@angular/material/icon';
@Component({
selector: 'app-dialog-close-button',
standalone: true,
imports: [
CommonModule,
MatButtonModule,
MatDialogModule,
MatIconModule,
],
templateUrl: './dialog-close-button.component.html',
styleUrl: './dialog-close-button.component.scss'
})
export class DialogCloseButtonComponent {}
dialog-close-button.component.html
<button mat-dialog-close mat-icon-button aria-label="Close dialog">
<mat-icon>close</mat-icon>
</button>
To utilize this functionality in your dialog template, simply include the following:
<h1 dialogTitle>Title of your dialog here</h1>
End Result:
https://i.sstatic.net/Y61ik.png
*Ensure you have imported DialogTitleDirective in your component or module.