Reputation: 1607
How do I initialize the child dropdown based on the value of the parent dropdown?
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 } });
}
}
Upvotes: 1
Views: 3940
Reputation: 1
use [ngModelOptions]="{standalone: true}" then it will bing with ngModel directly. Binding with event is not required
Upvotes: 0
Reputation: 6685
You have to initialize selectedState
with the first country from stateNames
in ngOnInit
:
this.selectedState = this.stateNames[0];
See Plunker
Upvotes: 1