2017-05-19 41 views
0

我正在嘗試一個角度項目,我需要顯示n個按鈕,並且點擊每個按鈕時它應該顯示按鈕編號。在事件綁定中傳遞參數到組件

有沒有辦法在事件綁定中傳遞任何靜態值,這可以在組件中用於決策。

<button (click)="clicked('want to pass a value here')">Click </button> 
<h1>The button number you entered is: {{buttonNumber}}</h1> 

這些值可以是:1,2 ...... n將用於控制器類中的決策。

+2

當然。你試過了嗎? –

+0

據我瞭解,我只是熟悉$事件,但我不需要在我的邏輯中的任何細節 –

+0

所以你在你的問題中嘗試代碼? –

回答

0

您擁有的代碼將起作用。您需要在組件中創建一個函數(在您的情況下稱爲click)並處理傳入的$事件。

從'@ angular/core'導入{Component,OnInit};

@Component({ 
    selector: 'example', 
    template: ` 
    <h1>The button number you entered is: {{buttonNumber}}</h1> 
    <button (click)="clicked('want to pass a value here')">Click</button> 
    ` 
}) 

export class ExampleComponent implements OnInit { 
    constructor() { } 

    ngOnInit() { } 

    clicked(yourText) { 
    // yourText is the argument from the template 
    console.log(yourText) 
    } 

} 
+0

解決了!非常感謝。 –

+0

沒問題@OnkarGhule!角度可以是一個痛苦的學習,但如果你每天堅持下去,它會開始走到一起。 PS。不要忘記標記這是答案:) – mikias