Angular2 ngModel选择

时间:2016-09-08 09:31:35

标签: angular

我不知道如何将所选值放到Object或Array中,如果我选择第一个选择器levelNum值将具有第一个选择的对象,如果我选择第二个,它将在内部有两个不同的数字用于分隔选择器但仍然是相同的ngModel名称。我需要这种方式用于从ng-for获得的动态选择器。这是我的代码:

//our root app component
import {Component, Directive, Output, EventEmitter, Input, SimpleChange} from 'angular2/core'
import {Observable} from 'rxjs/Observable';
import {Observer} from 'rxjs/Observer';
//import 'rxjs/Rx';
@Component({
  selector: 'my-app',
  template:`
    <h1>Selecting Number</h1>
    <select type="number" [(ngModel)]="levelNum" (ngModelChange)="toNumber()">
      <option *ngFor="let level of levels" [ngValue]="level.num">{{level.name}}</option>
    </select>
     <select type="number" [(ngModel)]="levelNum" (ngModelChange)="toNumber()">
      <option *ngFor="let level of levels" [ngValue]="level.num">{{level.name}}</option>
    </select>
    {{levelNum}}
  `,
})
export class AppComponent {
  levelNum: any;
  levels:Array<Object> = [
      {num: 0, name: "AA"},
      {num: 1, name: "BB"}
  ];
  toNumber(){
    this.levelNum = +this.levelNum;
    console.log(this.levelNum);
  }
}

1 个答案:

答案 0 :(得分:0)

我不能正确理解你的问题,但也许这个plunker会帮助你:

https://plnkr.co/edit/sGvWZoaP5EWDkkUJE0R2?p=preview

<Window.Resources>
        <Style x:Key="RectangleFill" TargetType="Rectangle">
            <Setter Property="Fill" Value="Blue" />
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=lblOk, Path=Text}" Value="OK">
                    <Setter Property="Fill" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <StackPanel>
        <TextBlock Name="lblOk" Text="OK" Foreground="Black" FontSize="20" FontWeight="Medium" />
        <Rectangle Width="100"
                   Height="50" Style="{StaticResource RectangleFill}">
            <Rectangle.Resources>

            </Rectangle.Resources>
        </Rectangle>
    </StackPanel>