[英]Angular - how to get value selected in dropdown menu?
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. 因此,如果他们选择“英语”,我希望它可以访问site.com/cn。 And if they choose Spanish I want it to go to site.com/es 如果他们选择西班牙语,我希望它可以访问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. 我尝试了该解决方案,并尝试了多种解决方案: 如何在Angular 5的Mat-Select Option中获取选定值的ID我也浏览了Angular材质文档,但对于该主题所需的一切都很少。
Why is the specific selection not being recognized? 为什么无法识别特定选择?
HTML : 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: 尝试将您的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 https://material.angular.io/components/select/api#MatSelect
Or you can use ngModel to access value directly in your function 或者您可以使用ngModel直接在函数中访问值
<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 在您的.ts文件中
onSelectChange(value) {
//if value selected is spanish
if(value == "es")
this.routerService.navigate(['es/']);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.