Home > database >  How to expand image using MatDialog?
How to expand image using MatDialog?

Time:06-08

So I'm currently making an image that, when clicked, it expands using MatDialog. I'm currently creating a new component to make the MatDialog, however, one thing bugs me.

In my main component's HTML, I have the image as shown in the code below:

<section  *ngIf="image">
  <div >
    <div >
      <img  [src]="image" alt="" (click)="openImage()" />
    </div>
  </div>

</section>

As seen, when the image is clicked, it triggers the openImage() in my typescript component:

openImage(){
this.dialog
  .open(DialogExpandImageComponent)
  .afterClosed()
  .subscribe(() => console.log("test successful"))
}

My issue here is that, for the Dialog that expands the image, I'm creating another HTML and TS.

The TS code is currently as follows:

import { Component } from '@angular/core';
import { MatDialogRef } from '@angular/material/dialog';

@Component({
  selector: 'app-dialog-expand-image',
  templateUrl: './dialog-expand-image.component.html',
  styleUrls: ['./dialog-expand-image.component.scss'],
})
export class DialogExpandImageComponent {
  constructor(public dialogRef: MatDialogRef<DialogExpandImageComponent>) {}

  closeImage() {
    this.dialogRef.close();
  }
}

In my HTML, I just put a "TEST" word and it works when I click the image (the TEST is displayed accordingly). My issue here is that I don't know how I'm going to bring the image that's on my other component (the main component above where the image can be clicked) to be shown in this current dialog component. If anyone has a good suggestion, I'd be bery thankful.

CodePudding user response:

You need to send the data when you perform the open dialog, and catch them in the dialog component by using injection token of MAT_DIALOG_DATA

// in other component
dialog.open(YourDialog, {
  data: { name: 'austin' },
});

// dialog component
import {Component, Inject} from '@angular/core';
import {MAT_DIALOG_DATA} from '@angular/material/dialog';

@Component({
  selector: 'your-dialog',
  template: 'passed in {{ data.name }}',
})
export class YourDialog {
  constructor(@Inject(MAT_DIALOG_DATA) public data: {name: string}) { }
}

// dialog template
<ng-template let-data>
  Hello, {{data.name}}
</ng-template>

For example if you have a thumbnail and you click it you will open the dialog and send the image url or image id and render it in the dialog template.

reference: enter image description here

  • Related