Richard77
Richard77

Reputation: 21661

How to access the width/heigh of a angular material dialog in the code

Is there a way to access the width/height of a dialog component, which is being styled in the css? This is how I'm creating the dialog

  this.dialogRef = this.dialog.open(MyComponent, {
    position: {
      top: yPos + 'px',
      left: xPos + 'px'
    }
  });

I'd like to know the width of the dialog. So far I'm using d3 to get the that information.

const dialog = d3.select('#my-dialog');
const bounds = (dialog.node() as HTMLElement).getBoundingClientRect();

Is there a way to do so without d3? I don't see anything in the dialog that can help. this.dialogRef.componentInstance has only one property: data.

Thanks for helping

Upvotes: 1

Views: 1285

Answers (1)

Akber Iqbal
Akber Iqbal

Reputation: 15041

You can get it via the DOM... so after calling this.dialog.open & then on each resize because a resize will have impact on the height and width

relevant TS:

import {  Component,  Inject,  HostListener,  OnInit} from "@angular/core";
import {  MatDialog,  MatDialogRef,  MAT_DIALOG_DATA} from "@angular/material/dialog";

export interface DialogData {
  animal: string;
  name: string;
}

/**
 * @title Dialog Overview
 */
@Component({
  selector: "dialog-overview-example",
  templateUrl: "dialog-overview-example.html",
  styleUrls: ["dialog-overview-example.css"]
})
export class DialogOverviewExample implements OnInit {
  animal: string;
  name: string;

  constructor(public dialog: MatDialog) {}

  openDialog(): void {
    const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
      width: "250px",
      data: { name: this.name, animal: this.animal }
    });
    let dialogDOME = <HTMLElement>(
        document.getElementsByClassName("mat-dialog-container")[0]
      );
    console.log(      " width: ",      dialogDOME.offsetWidth , " height: ",      dialogDOME.offsetHeight   );

    dialogRef.afterClosed().subscribe(result => {
      console.log("The dialog was closed");
      this.animal = result;
    });
  }

  @HostListener("window:resize", ["$event"])
  onResize(event: any) {
    if (document.getElementsByClassName("mat-dialog-container")) {
      let dialogDOME = <HTMLElement>(        document.getElementsByClassName("mat-dialog-container")[0]      );
      console.log(      " width: ",      dialogDOME.offsetWidth , " height: ",      dialogDOME.offsetHeight   );
    }
  }
  ngOnInit() {
  }

}

@Component({
  selector: "dialog-overview-example-dialog",
  templateUrl: "dialog-overview-example-dialog.html"
})
export class DialogOverviewExampleDialog {
  constructor(
    public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
    @Inject(MAT_DIALOG_DATA) public data: DialogData
  ) {}

  onNoClick(): void {
    this.dialogRef.close();
  }
}

complete working stackblitz

Upvotes: 1

Related Questions