1

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/']);
}
HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
angleUr
  • 449
  • 1
  • 8
  • 27
  • Maybe your navigate should be `this.routerService.navigate(['/es']);`. Are you getting any errors in the console? – R. Richards Nov 26 '19 at 23:45
  • Hi @R.Richards , thanks. I have some things to figure out with the specific address, however the main problem is actually that I cant get the value. There is no error in the console. And I put console.log's but they are not getting hit. Once I tried to alter the method to detect the value, it doesn't work at all anymore. – angleUr Nov 26 '19 at 23:48
  • 3
    Does this help you: https://stackoverflow.com/questions/50222738/angular-6-material-mat-select-change-method-removed. Looks like `(selectionChange)` should be on `mat-select` and not `mat-option` – R. Richards Nov 26 '19 at 23:53

2 Answers2

3

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>

https://material.angular.io/components/select/api#MatSelect

Damian C
  • 2,111
  • 2
  • 15
  • 17
2

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/']);
}
Mridul
  • 1,320
  • 1
  • 5
  • 19