mpace
mpace

Reputation: 93

Bind value on md-menu-item click Angular2 Material Design

Given the following code, how would I bind on click my selected option to selectedOption.name and selectedOption.value, respectively?

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>

Upvotes: 3

Views: 3211

Answers (1)

scarlz
scarlz

Reputation: 2512

You can use a click event on a button to set the selectedOption:

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

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

Note the ? elvis operator. This is used to prevent template errors from reading a property when selectedOption is not yet defined.

Upvotes: 7

Related Questions