Angular2级联选择

时间:2016-05-22 15:37:28

标签: angular cascadingdropdown

在Angular2中,我想为xs和ys的给定数组对象创建级联选择:

data:Array<Object> = 
  [
    {"x":50, "ys":[ 10, 15, 20, 25, 30, 35]},                                                                                                           
    {"x":75, "ys":[ 15,20,25,30,35,40,45]}
  ];

第一个选择用x填充,第二个选择用相应的y填充。

以下是x的选择代码。

  <select [(ngModel)]="x"> 
    <option *ngFor="#n of data" [attr.value]="n.x">{{n.x}}</option>
  </select>

如何根据选择的x值用ys来表示第二个选择?

我创建了plunkr

2 个答案:

答案 0 :(得分:2)

我会像这样利用selectedIndex:

<select [ngModel]="x" (ngModelChange)="x = $event; second.selectedIndex = 0" #first> 
   <option *ngFor="#n of data" [attr.value]="n.x">{{n.x}}</option>
</select>
<select [(ngModel)]="y" #second> 
   <option *ngFor="#n of data[first.selectedIndex].ys" [attr.value]="n">{{n}}</option>
</select>
...
export class App {
  x: number = 50;

  y: number = 10;

  data:Array<Object> = 
  [
    {"x":50, "ys": [10, 15, 20, 25, 30, 35]},                                                                                                           
    {"x":75, "ys": [15, 20, 25, 30, 35, 40, 45]},
    {"x":100, "ys": [25, 35, 40, 45, 55, 65]} 
  ];
}

另见工作示例https://plnkr.co/edit/W3avXWmcmWFpBhS14LGP?p=preview

语义UI版本https://plnkr.co/edit/4TIdWBNwk0wKR4ndKdzJ?p=preview

答案 1 :(得分:1)

这可能就是你要找的东西:

@Component({
  selector: 'my-app',
  providers: [],
  template: `
<select [(ngModel)]="x"> 
  <option *ngFor="let n of data" [ngValue]="n.x">{{n.x}}</option>
</select>

<select [(ngModel)]="y"> 
  <option *ngFor="let n of data[x == 50 ? 0 : 1].ys" [ngValue]="n">{{n}}</option>
</select>

<div>{{data[x == 50 ? 0 : 1].ys}}</div>

  `,
  directives: []
})
export class App {
  x = 50;
data:Array<Object> = [
    {"x":50, "ys":[ 10, 15, 20, 25, 30, 35]},                                                                                                           
    {"x":75, "ys":[ 15,20,25,30,35,40,45]}
  ];
}

Plunker example