Angular2 Cascading Select

2019-05-29 14:30发布

In Angular2, I want to create a cascading select for the given array object of xs and ys:

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

The first select is populated with x and second with the corresponding ys.

Following is the select code for x.

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

How to polulate the second select with ys based on the selcted x value?

I have created a plunkr

2条回答
ゆ 、 Hurt°
2楼-- · 2019-05-29 15:14

This might be what you are looking for:

@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

查看更多
太酷不给撩
3楼-- · 2019-05-29 15:23

I would leverage selectedIndex like this:

<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]} 
  ];
}

See also working example https://plnkr.co/edit/W3avXWmcmWFpBhS14LGP?p=preview

Semantic UI version here https://plnkr.co/edit/4TIdWBNwk0wKR4ndKdzJ?p=preview

查看更多
登录 后发表回答