Angular 6 component as a dialog (angular material dialogRef) and by itself at the same time. Is it possible?

Viewed 2649

I have a component that pefectly works by itself, but doesn't work as dialog.

When I use DI to inject dialogRef and MAT_DIALOG_DATA

constructor(
  public dialogRef: MatDialogRef<ChannelsComponent>,   
  @Inject(MAT_DIALOG_DATA) private data: any
) { }

it works as dialog only, but stops working by itself. When I try to render this component without dialog, I get:

StaticInjectorError(AppModule)

So, it works, but only in one role - either as a component by itself, or as a dialog, but not simultaneously.

The question is: can we use the same Angular component as dialog and by itself (without dialog) at the same time?

UPDATE:

Simplified versions:

https://stackblitz.com/edit/angular-kg32ui - works only as dialog, doesn't work if click on menu 'Channels'

https://stackblitz.com/edit/angular-sr9b8h - works as component and dialog, but doesn't provide data to the dialog

The only difference in 'channels.component.ts' that 1st version has these services injected to the constructor:

constructor(
  public dialogRef: MatDialogRef<ChannelsComponent>,
  @Inject(MAT_DIALOG_DATA) private data: any
) { }
1 Answers

The reason your component only works as a dialog when you add those dependencies, is that they're only injected when the component is opened as a dialog. When the component is used without a dialog, it's understandable that it can't find the dialogRef.

To get around this, I'd suggest opening an ng-template as the dialog content instead.

In order to do this, inside your html template create an ng-template:

<ng-template #dialog>
  <h1>Dialog content!</h1>
</ng-template>

After creating the template, you can access it from your component using the ViewChild decorator:

@ViewChild('dialog') template: TemplateRef<HTMLElement>;

You can also open it like you would any usual dialog:

this.dialogRef = this.dialog.open(this.template);

You can view a working example here: https://stackblitz.com/angular/nnorporgbvx

Related