鉴于以下代码,如何将我选择的选项分别点击selectedOption.name
和selectedOption.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>
答案 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
时读取属性。