Show Component with MatDialog service as popup
Prerequisites:
@angular/material v8.2.3
1. Redirection Service - TS
...
constructor(public dialog: MatDialog, private location: PlatformLocation, public translate: TranslateService) {
this.location.onPopState(() => {
const length = this.dialog.openDialogs.length;
if (!this.ignorePop) {
if (length > 0) {
this.dialog.openDialogs[length - 1].componentInstance.closePopup();
}
} else {
this.ignorePop = false;
}
});
}
// Method to open component
open(title: string, componentType: string, options?: { [key: string]: any }): void {
let translate = this.translate.instant(title);
if (translate.includes('[' + title + ']')) {
translate = title;
}
const dialogRef = this.dialog.open(RedirectionDialogComponent, {
data: { title: translate, component: getComponent(componentType)},
maxWidth: '90%',
width: '90%',
height: 98.5 - this.dialog.openDialogs.length * 1.5 + '%',
hasBackdrop: false,
closeOnNavigation: false,
});
}
.......
this.location.onPopState(() => {
const length = this.dialog.openDialogs.length;
if (!this.ignorePop) {
if (length > 0) {
this.dialog.openDialogs[length - 1].componentInstance.closePopup();
}
} else {
this.ignorePop = false;
}
});
}
// Method to open component
open(title: string, componentType: string, options?: { [key: string]: any }): void {
let translate = this.translate.instant(title);
if (translate.includes('[' + title + ']')) {
translate = title;
}
const dialogRef = this.dialog.open(RedirectionDialogComponent, {
data: { title: translate, component: getComponent(componentType)},
maxWidth: '90%',
width: '90%',
height: 98.5 - this.dialog.openDialogs.length * 1.5 + '%',
hasBackdrop: false,
closeOnNavigation: false,
});
}
.......
2. Redirection Dialog Component - TS
export interface DialogData {
title: string;
component: Type<any>;
parameters: { [key: string]: any };
}
@Component({
selector: 'redirection-dialog',
templateUrl: './redirection-dialog.component.html',
styleUrls: ['./redirection-dialog.component.scss']
})
export class RedirectionDialogComponent implements OnInit {
@ViewChild('contentComponent', { static: true, read: ViewContainerRef }) contentComponent!: ViewContainerRef;
constructor(
public dialogRef: MatDialogRef<RedirectionDialogComponent >,
@Inject(MAT_DIALOG_DATA) public data: DialogData,
public dialog: MatDialog,
private componentFactoryResolver: ComponentFactoryResolver,
private el: ElementRef
) {}
ngOnInit(): void {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(this.data.component);
this.contentComponent.clear();
const compRef = this.contentComponent.createComponent(componentFactory);
}
}
3. Redirection Dialog Component - HTML
<div>
<h1> {{data.title}} </h1>
<mat-dialog-content>
<div #contentComponent></div>
</mat-dialog-content>
</div>
3.1 Example of use:
In your code:
...
this.redirectionService.open('Your component title', 'YourComponent');
...
Δεν υπάρχουν σχόλια:
Δημοσίευση σχολίου
What may be missing, or could get better?