2016-11-14 51 views
0

鑑於以下代碼,我將如何綁定點擊我選擇的選項分別爲selectedOption.nameselectedOption.value在md-menu-item上綁定值點擊Angular2 Material Design

app.component.ts:

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 

    options = [ 
    { 
     name: 'test1', 
     value: "This is test1's value" 
    }, 
    { 
     name: 'test2', 
     value: "This is test2's value" 
    }, 
    { 
     name: 'test3', 
     value: "This is test3's value" 
    } 
    ] 
} 

app.component.html:

<button md-icon-button [md-menu-trigger-for]="menu"> 
    <md-icon>comment</md-icon> 
</button> 
<md-menu #menu="mdMenu"> 
    <div *ngFor="let option of options"> 
    <button md-menu-item>{{option.name}}</button> 
    </div> 
</md-menu> 

<h3>Your selected option: </h3> 
<p>{{selectedOption.name}}: {{selectedOption.value}}</p> 

回答

3

您可以在按鈕中使用點擊事件設置selectedOption

<div *ngFor="let option of options"> 
    <button md-menu-item (click)="selectedOption = option"> 
    {{option.name}} 
    </button> 
</div> 

<p>{{selectedOption?.name}}: {{selectedOption?.value}}</p> 

請注意? elvis操作員。當selectedOption尚未定義時,這用於防止模板錯誤讀取屬性。

+0

這工作完美 - 謝謝。 – mpace