Angular 2问题获取选择选项值

时间:2016-12-02 02:49:37

标签: angular

我有一个选择

<select name='shape_id' ngModel (change)='changeShape($event.target.value)'>
  <option *ngFor="let shape of shapes" [ngValue]="shape.id">{{shape.name}}</option>
</select>

这是数据。

  shapes = [
    {id:'1', name:'Angle'},
    {id:'2', name:'Bar'},
   ];

我无法获得价值。

 changeShape(shape){
    console.log(shape);
  }

这输出&#34; 0:1&#34;,但我希望值为1。

以下是检查器中的选项。

<option value="0: 1" ng-reflect-ng-value="1">Angle</option>

如何获取id值1?

2 个答案:

答案 0 :(得分:6)

将[ngValue]更改为[value]

  <select name="shape_id" (change)="changeShape($event.target)">
    <option *ngFor="let shape of shapes" [value]="shape.id">
      {{shape.name}}
    </option>
  </select>

并塑造shape.value。

changeShape(shape){
  console.log(shape.value);
}

答案 1 :(得分:0)

除非您真的想在值更改时执行某些操作,否则您实际上不需要订阅“更改”事件。但是,如果你想要的只是选择值,那么用ngModel将它绑定到组件属性就足够了。

组件:

import {Component} from '@angular/core';

@Component({
  selector: 'home',
  styleUrls: ['./home.component.css'],
  templateUrl: './home.component.html'
})
export class HomeComponent {

    shapes = [
        {id:'1', name:'Angle'},
        {id:'2', name:'Bar'},
    ];

    shape: string;

    onSelect() {
        // log updated value
        console.log(this.shape);
    }

}

模板:

<select name='shape_id' [(ngModel)]="shape" (change)="onSelect()">
  <option *ngFor="let shape of shapes" [value]="shape.id">{{shape.name}}</option>
</select>