Blair Osbay
Blair Osbay

Reputation: 227

Two comboboxes showing nested arrays in AngularJS

I have an array which as arrays as members:

[
  {"group":"Canada","data":[{"value":"Ontario","description":"Toronto"},
                            {"value":"Quebec","description":"Quebec City"},
                            {"value":"Manitoba","description":"Winnipeg"}
                           ]
  },
  {"group":"Mexico","data":[{"value":"Jalisco","description":"Guadalajara"},
                            {"value":"Nayarit","description":"Tepic"}
                           ]
  },
  {"group":"United States of America","data":[
                            {"value":"Alabama","description":"Montgomery"},
                            {"value":"Georgia","description":"Atlanta"},
                            {"value":"Mississippi","description":"Jackson"},
                            {"value":"Louisiana","description":"Baton Rouge"},
                            {"value":"Texas","description":"Ausint"}
                           ]
  }
]

I would like to have an AngularJS combobox which shows the list of group countries. When users select each country, I would like another combo to show the names of regions in that country.

Can anybody point me to tutorials which show how to achieve it?

Upvotes: 1

Views: 28

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657977

Plunker example

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

      <select [(ngModel)]="selectedData">
        <option *ngFor="let item of getData()" [ngValue]="item">{{item.value}}</option>
      </select>

    </div>
  `,
  directives: []
})
export class App {
  selectedGroup;
  selectedData;

  groups = [
...
];
  constructor() {
    this.name = 'Angular2 (Release Candidate!)'
  }

  getData() {
    let idx = this.groups.indexOf(this.selectedGroup);
    if(idx >= 0) {
      console.log(this.groups[idx]);
      return this.groups[idx].data;
    }
  }
}

Upvotes: 1

Related Questions