在md-menu-item上绑定值单击Angular2 Material Design

时间:2016-11-14 22:47:15

标签: javascript angular material-design

鉴于以下代码,如何将我选择的选项分别点击selectedOption.nameselectedOption.value

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>

1 个答案:

答案 0 :(得分:6)

您可以使用按钮上的点击事件来设置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时读取属性。