Issue
I want to change dropdown based on another dropdown.
ts.file
Countries: Array<any> = [
{ name: '1st of the month', states: [ {name: '16th of the month'} ] },
{ name: '2nd of the month', states: [ {name: '17th of the month'} ] },
{ name: '3rd of the month', states: [ {name: '18th of the month'} ] },
]
states: Array<any> = [];
cities: Array<any> = [];
changeCountry(country: any) {
this.states = this.Countries.find(cntry => cntry.name == country.target.value).states;
}
html.file
<mat-form-field>
<mat-select [(ngModel)]="custFirst" name="custFirst" placeholder="Country" (change)="changeCountry($event)">
<mat-option *ngFor="let country of Countries" [value]="country.name" > {{ country.name }}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-select placeholder="State">
<mat-option *ngFor="let state of states" [value]="state.name">{{ state.name }}
</mat-option>
</mat-select>
</mat-form-field>
Now my problem is that, I unable to get the value in second dropdown. Please help me why trigger part is not working.

Solution
The change event should be changed to selectionChange. If you want the state to be auto-selected add [(ngModel)] to the state dropdown and update it when the country is changed:
changeCountry(country: any) {
this.states = this.Countries.find(
(cntry) => cntry.name == country.value
).states;
this.sFirst = this.states[0].name;
}
<mat-form-field>
<mat-select [(ngModel)]="custFirst" name="custFirst" placeholder="Country" (selectionChange)="changeCountry($event)">
<mat-option *ngFor="let country of Countries" [value]="country.name" > {{ country.name }}</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field>
<mat-select placeholder="State" [(ngModel)]="stateFirst">
<mat-option *ngFor="let state of states" [value]="state.name">{{ state.name }}
</mat-option>
</mat-select>
</mat-form-field>
Working example: https://stackblitz.com/edit/angular-6-stackoverflow-nzvqse?file=src/app/components/stackoverflow-solution/stackoverflow-solution.component.ts
Answered By - deepakchethan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.