How can one retrieve the selected value from a dropdown menu in Angular?

Objective: My goal is to create a dropdown menu where users can select a value, which will then dynamically change the address of the website based on their selection.

Issue: Although I managed to make the address change upon selection, it did so for every option chosen. The desired outcome is for each selection to lead to a different address, such as site.com/en for "English" and site.com/es for "Spanish".

Attempts Made:

I have experimented with solutions found at How to get Id of selected value in Mat-Select Option in Angular 5 and reviewed Angular material documentation, although it lacked detailed information on this specific functionality.

Why isn't the specific selection 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 == "es")
      this.routerService.navigate(['es/']);
}

Answer №1

Consider relocating your selectionChanged event listener to the select element instead of 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

Answer №2

Alternatively, you have the option to utilize ngModel for direct access to the value within 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>

In your .ts file

onSelectChange(value) {
//if the selected value is 'es' for Spanish
  if(value == "es")
    this.routerService.navigate(['es/']);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Angular Material date picker unpredictably updates when a date is manually changed and the tab key is pressed

My component involves the use of the Angular material date picker. However, I have encountered a strange issue with it. When I select a date using the calendar control, everything works fine. But if I manually change the date and then press the tab button, ...

Exporting declarations and different export types within a TypeScript ambient module

I am currently working on adding specific types for the config module in our application. The config module is generated dynamically from a JSON file, making it challenging to type. Since it is a node module, I am utilizing an ambient module for the typing ...

Nesting objects within arrays using Typescript Generics

Hello, I am currently attempting to assign the correct type to an object with nested values. Here is a link to the code in the sandbox: https://codesandbox.io/s/0tftsf interface Product { name: string, id: number productList?:ProductItem[] } interf ...

Transform a collection of interfaces consisting of key-value pairs into a unified mapped type

I have a set of interfaces that describe key-value pairs: interface Foo { key: "fooKeyType", value: "fooValueType", } interface Bar { key: "barKeyType", value: "barValueType", } interface Baz { key: "bazKeyType", value: "bazValue ...

Validating React Typescript Props: Ensuring that two specific props do not exist simultaneously

Currently, I'm developing a reusable component in React-Typescript and I am looking to validate my props OnClick and component as follows: Both onClick and component prop are optional. These props will only be passed to the component if they need to ...

Whenever comparing the types 'string[]' and 'DeliveryTypeEnum', this condition will consistently result in 'true' as there is no intersection between the two. This is highlighted by the error code ts(2367)

Hello everyone, I'm a junior developer and could use some assistance if (query.deliveryType && query.deliveryType != DeliveryTypeEnum.EITHER) { search.push({ terms: { "deliveryType.keyword&q ...

Protractor fails to capture the presence of mat-dialog-container

My Protractor test for an Angular 5 application is functioning well, except when it has to handle a popup containing input fields. The HTML element representing the popup looks like this: <mat-dialog-container class="mat-dialog-container ng-tns-c26-5 n ...

Properly configuring paths in react-native for smooth navigation

When working on my React-Native project, I noticed that my import paths look something like this: import { ScreenContainer, SLButton, SLTextInput, } from '../../../../../components'; import { KeyBoardTypes } from '../../../../../enums ...

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

When using Angular's `createComponent()` method, an error may be thrown with the message "ERROR TypeError: Cannot add

I am currently working on a project where I am dynamically creating components. The component's class is being passed via an ngrx action and the process involves: loadComponent(componentType: Type<any>): void { const viewContainerRef = this.co ...

Utilizing Angular CLI configuration for End-to-End testing purposes

I'm currently in the process of updating an Angular CLI project to version 6 The issue I'm facing is that prior to version 6, I could run the command ng e2e -e=e2e and the tests would execute smoothly with the specified environment. However, in ...

What connections exist between systemjs.config.js and .import() in Angular2/SystemJS?

My journey to learn Angular2 has led me to various Stack Exchange posts and internet articles discussing the function of systemjs.config.js. However, I've noticed that most explanations tend to use the term "app" excessively. For example, when index. ...

Retrieve data from a table within an Angular component

Struggling with the ng2-smart-table library, I am facing challenges in passing values entered in the edit line to a custom component: Refer to the code snippet below for passing Maximum and Minimum Temperature values to the SmartTableEditorFunctionsCompon ...

Ways to Access HTTP Request Headers in Angular 6 upon Page Load

Is it possible to retrieve request header information in Angular 6/7 upon application initialization? I specifically require access to header values for security and access management purposes, as these values are set in the headers during the usage of th ...

When using Protractor with Typescript, you may encounter the error message "Failed: Cannot read property 'sendKeys' of undefined"

Having trouble creating Protractor JS spec files using TypeScript? Running into an error with the converted spec files? Error Message: Failed - calculator_1.calculator.prototype.getResult is not a function Check out the TypeScript files below: calculato ...

Element remains intact after DOM manipulation even during router navigation

One of my directives has the functionality to relocate the element it is applied to on the body of the document: @Directive({ selector: '[myDirective]' }) export class MyDirective implements AfterViewInit { constructor(private elem: ElementR ...

Challenge with Routing in Angular 2

I'm dealing with a route setup like this: path: 'something/:id/somethingElse' In my header.component.html, I need to include a link to this page. I tried the following approach: <a routerLink="['something',myIdThatIsDynamicO ...

The Angular test spy is failing to be invoked

Having trouble setting up my Angular test correctly. The issue seems to be with my spy not functioning as expected. I'm new to Angular and still learning how to write tests. This is for my first Angular app using the latest version of CLI 7.x, which i ...

Closing the side navigation bar when a router link is clicked on small devices

In my project, I have implemented the side-nav component for routing between different components. Here is how it looks: https://i.stack.imgur.com/v6hE8.png However, I am currently facing an issue with the side-nav. On mobile devices, the side-nav appear ...

A guide on showcasing nested arrays data in an Angular application

info = [ { list: [ { title: 'apple'} ] }, { list: [ { title: 'banana'} ] } ] My goal here is to extract the list items. Here is how they are structured. desired r ...