Goal : I want to be able to have the user click a value in a dropdown, that will change the address of the site they are on, based on the selection.
Problem : I was able to get it to change the address, but it would do it no matter what selection they made. I want it to go to a different address for each selection.
So if they choose "English" I want it to go to site.com/en. And if they choose Spanish I want it to go to site.com/es
What I tried :
I tried the solution, and many variations of it from: How to get Id of selected value in Mat-Select Option in Angular 5 I also looked through Angular material documentation but it is a bit sparse on everything needed for this topic.
Why is the specific selection not being recognized?
HTML :
<mat-form-field class="right">
<mat-select>
<mat-option *ngFor="let language of languages" [value]="language.value" (selectionChange)="doSomething($event.value)">
{{language.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
TypeScript :
doSomething(event) {
//if value selected is spanish
if(event.value == "es")
this.routerService.navigate(['es/']);
}
Try moving your selectionChanged to your select, not the option:
<mat-form-field class="right">
<mat-select (selectionChange)="doSomething($event)">
<mat-option *ngFor="let language of languages" [value]="language.value" >
{{language.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
Or you can use ngModel to access value directly in your function
<mat-form-field class="fullwidth" required>
<mat-label>Select</mat-label>
<mat-select [(ngModel)]="selectedItem" (ngModelChange)="onSelectChange(selectedItem)">
<mat-option *ngFor="let obj of testArray" [value]="obj.value">
{{obj.name}}
</mat-option>
</mat-select>
</mat-form-field>
On your .ts file
onSelectChange(value) {
//if value selected is spanish
if(value == "es")
this.routerService.navigate(['es/']);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.