How to determine, if an Angular Component is opened as dialog?

1.1k Views Asked by At

I want to implement an Angular component, which can be opened both as a MatDialog, or displayed normally. If it's opened as a dialog, I want to display a close button for the user, to be able to close the dialog. To implement this, I have to inject the MatDialogRef service into the component.(If I try to inject it in all of the 2 scenarios and the component is opened via the router, it throws an error.)

I found a solution where I inject the MatDialogRef service conditionally. In this solution I have to use an Input parameter, which determines if the Component is opened as a dialog.

My question is the following:

Is there another way for the component, to determine if it is opened as a dialog, so the input parameter is not nessecary anymore, and the component is more self contained?

My code: The parent component opening the dialog:

openCutDataViewer(cutterPackageNumber: number) {
    let tempCutterPackageNumber = 12312432423;
    const dialogRef = this.dialog.open(CutterPackageDetailsComponent, {
      width: '95vw',
      maxWidth: '95vw !important',
      height: '95vh',
    });
dialogRef.componentInstance.openedAsDialog = true;
    dialogRef.componentInstance.cutterPackageNumber = tempCutterPackageNumber;
    
  }

The dialog/normal component:

import { Component, Injector, Input, OnInit } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';
import { InsulationCheckService } from '../insulation-check.service';
import { CutterPackage } from '../models/cutter-package.model';

@Component({
  selector: 'app-cutter-package-details',
  templateUrl: './cutter-package-details.component.html',
  styleUrls: ['./cutter-package-details.component.scss'],
})
export class CutterPackageDetailsComponent implements OnInit {
  @Input() cutterPackageNumber?: number;
  @Input() openedAsDialog: boolean = false;

  dialogRef?: MatDialogRef<CutterPackageDetailsComponent>;
  data?: CutterPackage;

  constructor(
    private insulationCheckService: InsulationCheckService,
    private injector: Injector
  ) {}

  ngOnInit(): void {
    //if insulation packageNumer is provided as input
    if (this.cutterPackageNumber) {
      this.insulationCheckService
        .getCutterPackageData(this.cutterPackageNumber)
        .subscribe((cutterPackage) => (this.data = cutterPackage));
    }

    //if opened as dialog, inject dialog service
    if (this.openedAsDialog) {
      this.dialogRef = <MatDialogRef<CutterPackageDetailsComponent>>(
        this.injector.get(MatDialogRef)
      );
    }
  }

  closeDialog() {
    if (this.dialogRef) {
      this.dialogRef.close();
    }
  }
}

0

There are 0 best solutions below