Commits
Nicolai Olsen authored 57bd2178c77
1 - | import {Injectable, TemplateRef} from '@angular/core'; |
1 + | import {Injectable, NgZone, TemplateRef} from '@angular/core'; |
2 2 | import {Observable, Subject} from 'rxjs'; |
3 - | import {DialogComponent} from './dialog.component'; |
4 3 | import {MatDialog, MatDialogConfig, MatDialogRef} from '@angular/material/dialog'; |
5 4 | import {ComponentType} from '@angular/cdk/portal'; |
6 5 | |
7 6 | type Dialog<T> = {subject: Subject<T|undefined>, dialog_service_identifier: string}; |
8 7 | |
9 8 | @Injectable({ |
10 9 | providedIn: 'root' |
11 10 | }) |
12 11 | export class DialogService { |
13 12 | private dialogs: Record<string, MatDialogRef<Dialog<any>>> = {}; |
14 13 | |
15 - | constructor(public materialDialog: MatDialog) {} |
14 + | constructor(public materialDialog: MatDialog, private zone: NgZone) {} |
16 15 | |
17 16 | public show<T>(dialogType: ComponentType<any> | TemplateRef<any>, configuration?: MatDialogConfig): Observable<T> { |
18 - | const dialog = this.materialDialog.open(dialogType, Object.assign({width: '400'}, configuration || {} ) ); |
19 - | dialog.componentInstance.dialog_service_identifier = `dialog_${new Date().getTime()}`; |
20 - | this.dialogs[(dialog.componentInstance as any).dialog_service_identifier] = dialog; |
21 - | return dialog.afterClosed(); |
17 + | // Now using NgZone to avoid weird bug where ngOnInit would only be called after dialog was closed, |
18 + | // thus rendering an empty unusable dialog |
19 + | return this.zone.run(() => { |
20 + | const dialog = this.materialDialog.open(dialogType, Object.assign({width: '400'}, configuration || {} ) ); |
21 + | dialog.componentInstance.dialog_service_identifier = `dialog_${new Date().getTime()}`; |
22 + | this.dialogs[(dialog.componentInstance as any).dialog_service_identifier] = dialog; |
23 + | return dialog.afterClosed(); |
24 + | }); |
22 25 | } |
23 26 | |
24 27 | public close<T>(dialog: any, value?: T): void { |
25 28 | if (dialog) { |
26 29 | this.getDialog(dialog).close(value); |
27 30 | } |
28 31 | } |
29 32 | |
30 33 | private getDialog(dialog: any): MatDialogRef<any> { |
31 34 | const result = this.dialogs[dialog.dialog_service_identifier]; |