PrimeNG级联下拉菜单:初始化子下拉列表

时间:2018-04-06 06:09:54

标签: dropdown primeng

如何根据父下拉列表的值初始化子下拉列表?

app.component.html

<p-dropdown [options]="states" [(ngModel)]="selectedState" (onChange)="getCities($event.value)"></p-dropdown>
<p-dropdown [options]="cities"></p-dropdown>

app.component.ts

export class AppComponent implements OnInit {

  cities: SelectItem[];
  selectedState: string;

  stateNames = ['Alabama', 'Alaska', 'California'];
  states = this.stateNames.map((val, i, stateNames) => {
      return { label: val, value: val }
  });  
  cityNames = [
    {state: 'Alabama', city: 'Birmingham'}, 
    {state: 'Alabama', city: 'Huntsville'}, 
    {state: 'Alabama', city: 'Montgomery'},
    {state: 'Alaska', city: 'Anchorage'}, 
    {state: 'Alaska', city: 'Juneau'},
    {state: 'California', city: 'Fresno'},
    {state: 'California', city: 'Perris'}
  ];

  ngOnInit() {
    this.getCities(this.selectedState);
  }

  getCities(state):any[] {
    this.cities = this.cityNames
                      .filter((el) => { return el.state === state })
                      .map((el) => { return { label: el.city, value: el.city } });
  }  
}

Plunker example

1 个答案:

答案 0 :(得分:1)

您必须使用selectedStatestateNames的第一个国家/地区初始化ngOnInit

this.selectedState = this.stateNames[0];

请参阅Plunker