在Angular2中实现下拉列表

时间:2016-05-30 04:50:50

标签: angular

是否有更好的方法在Angular2中实现下拉列表

我正在做以下

在模板中

<select (change)="onSelect($event.target.value)">
                      <option *ngFor="#taskstatus of dropdownValues" [value]="taskstatus.value">{{taskstatus.name}}</option>
</select>

在组件类

export class CreateTaskComponent {

    public selectedStatus: Taskstatus = this.dropdownValues[0];
    public dropdownValues: Taskstatus[] = [
         {"name":"OPEN","value":"OPEN"},
         {"name":"CLOSED","value":"CLOSED"}
    ];

    onSelect(taskevent) { 
        this.selectedStatus = null;
        for (var i = 0; i < this.dropdownValues.length; i++)
        {
          if (this.dropdownValues[i].value == taskevent) {
            this.selectedStatus = this.dropdownValues[i];
            console.log(this.selectedStatus.value);
          }
        }
    }
}

class Taskstatus{
  name: string;
  value: string;
}    

有更简单的方法吗?

1 个答案:

答案 0 :(得分:1)

使用ngModelngValue之类的:

<select [(ngModel)]="selectedStatus">
  <option *ngFor="#taskstatus of dropdownValues" [ngValue]="taskstatus">{{taskstatus.name}}</option>
</select>