exidion
exidion

Reputation: 31

How to get different output from one click event in Angular with more than one component?

I have no idea how to display a pop-up window with various content using the same method. I have two components - first one contains a form with some info links.

form-component.html

<a href="" (click)="openInfoPopup()">Info</a>
...
<a href="" (click)="openInfoPopup()">Info</a>
...
<a href="" (click)="openInfoPopup()">Info</a>

form-component.ts

openInfoPopup() {
...
let dialogRef = dialog.open(MyDialogComponent, dialogConf)
}

It works perfectly - openInfoPopup() opens my dialog as I want, but my poor knowlegde of Angular so far doesn't allow me to take the next step. Depending on which link you click, my popup should contain another text message. Clicking first link should open new dialog with first element of array below etc. In the second component, I created an array with my messages:

my-dialog-component.ts

infoArr = ["Text1", "Text2", "Text3", "Text4", "Text5", "Text6"];

my-dialog-component.html

<p *ngFor="let message of infoArr; let i = index"> {{ }} </p>

What should I do to make it work? How can I transfer data from my array to form-component and what I need to insert into my-dialog-component.html interpolation?

Upvotes: 0

Views: 412

Answers (1)

Kurt Hamilton
Kurt Hamilton

Reputation: 13515

The first thing to do here is parameterise your openInfoPopup() calls. The parameter would be whatever the unique key is for the different types. I'll use a string for simplicity.

form-component.html

<a href="" (click)="openInfoPopup('type1')">Info</a>
...
<a href="" (click)="openInfoPopup('type2')">Info</a>
...
<a href="" (click)="openInfoPopup('type3')">Info</a>

form-component.ts

selectedType: string;

openInfoPopup(type: string): void {
  this.selectedType = type;

  // open dialog
}

Once you know what the source of the event is, you can pass that information to the dialog.

Edit:

You've now clarified that you're using Angular Material.

In which case, you pass the key in via the open() function:

openInfoPopup(type: string) {
  this.selectedType = type;

  const dialogConf = new MatDialogConfig();
  dialogConf.width = "480px";
  let dialogRef = this.dialog.open(MyDialogComponent, {
    width: '480px',
    data: { type: this.selectedType }
  });
}

From the docs, you can access injected information like this:

export class YourDialog {
  constructor(@Inject(MAT_DIALOG_DATA) public data: any) { }
}

Upvotes: 1

Related Questions