首页 > 解决方案 > Angular - 如何在下拉菜单中选择值?

问题描述

目标:我希望能够让用户单击下拉列表中的值,这将根据选择更改他们所在站点的地址。

问题:我能够让它更改地址,但无论他们做出什么选择,它都会这样做。我希望它为每个选择转到不同的地址。

因此,如果他们选择“英语”,我希望它转到 site.com/en。如果他们选择西班牙语,我希望它转到 site.com/es

我尝试了什么

我尝试了该解决方案,以及它的许多变体:How to get Id of selected value in Mat-Select Option in Angular 5 我还查看了 Angular 材料文档,但对于本主题所需的所有内容都有些稀疏。

为什么不识别特定的选择?

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>

打字稿

doSomething(event) {
   //if value selected is spanish
   if(event.value == "es")
      this.routerService.navigate(['es/']);
}

标签: angulartypescriptangular-material

解决方案


尝试将您的 selectionChanged 移动到您的选择,而不是选项:

<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


推荐阅读