<select #selectedfiscalyear multiple>
<option *ngFor="let fiscalyear of fiscalyears" value = {{fiscalyear.value}}>
{{fiscalyear.value}}
</option>
</select>
<button class="btnView">Click</button>
其中
fiscalyears = [
{
"year": "fiscalYear",
"value": "2018"
},
{
"year": "fiscalYear",
"value": "2017"
},
{
"year": "fiscalYear",
"value": "2016"
},
{
"year": "fiscalYear",
"value": "2015"
},]
那么,如何在按钮点击事件中获取多个选定值(如2018,2017,2016等)?
答案 0 :(得分:2)
在这种情况下,您应该使用ngModel
。你甚至不需要按钮动作。
@Component({
selector: 'my-app',
template: `
<select #selectedfiscalyear multiple [(ngModel)]="selectedVal">
<option *ngFor="let fiscalyear of fiscalyears">
{{fiscalyear.value}}
</option>
</select>
<h1>{{ selectedVal }}</h1>
`
})
<强> Plunker code 强>
如果,您真的想在按钮点击时调用该功能,请使用以下代码:
@Component({
selector: 'my-app',
template: `
<select #selectedfiscalyear multiple [(ngModel)]="selectedVal">
<option *ngFor="let fiscalyear of fiscalyears">
{{fiscalyear.value}}
</option>
</select>
<button class="btnView" (click)="selectedVal.length ? select() : null">Click</button>
<input id="result">
`,
})
export class App {
constructor() {}
select(){
document.getElementById('result').value = this.selectedVal;
}
}
<强> Plunker code 2 强>