簡體   English   中英

如何從具有多個組件的 Angular 中的一個單擊事件獲得不同的輸出?

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

我不知道如何使用相同的方法顯示包含各種內容的彈出窗口。 我有兩個組件 - 第一個包含一個帶有一些信息鏈接的表單。

表單組件.html

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

表單組件.ts

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

它工作得很好 - openInfoPopup()根據需要打開我的對話框,但是到目前為止我對 Angular 的知識貧乏不允許我進行下一步。 根據您單擊的鏈接,我的彈出窗口應包含另一條短信。 單擊第一個鏈接應該打開新對話框,其中包含數組的第一個元素等。在第二個組件中,我用我的消息創建了一個數組:

我的對話框component.ts

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

我的對話框組件.html

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

我該怎么做才能讓它發揮作用? 如何將數據從我的數組傳輸到表單組件以及我需要插入到my-dialog-component.html插值中的內容?

這里要做的第一件事是參數化您的openInfoPopup()調用。 該參數將是不同類型的唯一鍵。 為簡單起見,我將使用字符串。

表單組件.html

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

表單組件.ts

selectedType: string;

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

  // open dialog
}

一旦您知道事件的來源是什么,您就可以將該信息傳遞給對話框。

編輯:

您現在已經澄清您正在使用 Angular Material。

在這種情況下,您可以通過open()函數傳入密鑰:

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 }
  });
}

從文檔中,您可以訪問注入的信息,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM