Search code examples
angularcascadingdropdown

Angular2 Cascading Select


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


Solution

  • 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