如何根据父下拉列表的值初始化子下拉列表?
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 } });
}
}
答案 0 :(得分:1)
您必须使用selectedState
中stateNames
的第一个国家/地区初始化ngOnInit
:
this.selectedState = this.stateNames[0];
请参阅Plunker