How to Update the Dropdown Selection in Angular 10 Using Angular Material without Modifying the List of Selected Options?

Recently started learning Angular and facing some challenges in understanding a particular concept.

I am looking to create a dropdown menu with a list of options to choose from. Once an item is selected, it should be abbreviated in the dropdown box. For example, selecting Ohio would display OH after selection. However, when revisiting the dropdown, the full state name should still show up. I've attempted using click events and ngModelChange but haven't been successful. Any assistance would be greatly appreciated!

HTML:

<section *ngFor="let row of dataSource; let i = index">
<div class="column-state">
    <mat-select (click)="changeFn(state)" placeholder="Choose State" [(ngModel)]="row.state">
      <mat-option [value]="state.full" *ngFor="let type of stateList">
        {{ state.full }}
      </mat-option>
    </mat-select>
  </div>
</section>

Variable -

hi:any;
stateList= [
{full:'Ohio', short: 'OH'},{ full:'Minnesota', short:'MN'}, {full: 'California', short: 'CA'}];

function attempted -
 changeFn(test:any) {
      this.hi = test;
  }

Answer №1

To implement this functionality in your template, you need to check if the selected option matches the current option.

<mat-select placeholder="Choose State" [(ngModel)]="selectedState">
  <mat-option [value]="state.full" *ngFor="let state of stateList">
    {{ selectedState === state.full ? state.short : state.full }}
  </mat-option>
</mat-select>

In your component's TypeScript file:

export class SelectExampleComponent {

  selectedState: string = '';

  stateList = [
    { full: 'Ohio', short: 'OH' },
    { full: 'Minnesota', short: 'MN' },
    { full: 'California', short: 'CA' }
  ];

}

I have renamed the variable used for storing the selection to selectedState, feel free to modify it based on your model.

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 parameter type { read?: any } cannot be assigned with the argument type { static: boolean; } in this context

I recently created a new Angular application and attempted to implement the angular-calendar by mattlewis92 for creating a calendar. I followed all the steps and copied the code from his GitHub repository: . However, I encountered an error on the first lin ...

Angular2 Application refreshing upon triggering an event

As a newcomer to Angular2 and SPA development, please forgive me if this question seems silly. I am currently following a tutorial where multiple components are being used. When clicking on an element, an event is supposed to be emitted and subsequently c ...

The Open AI API is currently inaccessible due to a missing API

After using OpenAI in numerous projects for some time, I decided to create a new apiKey for my latest project. However, upon initializing OpenAI, I encountered the following error: Unhandled Runtime Error Error: The OPENAI_API_KEY environment variable is ...

Having trouble with Nextjs API Integration - encountering error 404

I'm currently facing a major issue and I've hit a dead end. I've been spending days trying to connect my local nextjs 14 app to the CVENT API, but I keep receiving a persistent 404 error. Here's what is displayed in the frontend console ...

The specified property 'nodeName' is not recognized within the data type 'EventTarget'

In the code snippet below, we are checking whether the user is interacting with an input field, textarea, or contenteditable element. If any of these conditions are met, we should clear out the keys array and stop the script execution. let keys: any[] = [] ...

Issue with SvelteKit: PageData not being refreshed in API response after initial render

I am relatively new to working with Svelte and SvelteKit, and I am currently trying to fetch data from an API. I have followed the SvelteKit todo sample code, which works well for the initial rendering and when clicking on an a tag. However, I am facing an ...

The output of `.reduce` is a singular object rather than an array containing multiple objects

Building on my custom pipe and service, I have developed a system where an array of language abbreviations is passed to the pipe. The pipe then utilizes functions from the site based on these abbreviations. Here is the parameter being passed to the pipe: p ...

Unable to utilize the Object.values method with an object in TypeScript

I am attempting to create an array of values from all the keys within an object by using the Object.values(obj) function, but I encountered the following error message: No overload matches this call. Overload 1 of 2, '(o: { [s: string]: string; } | ...

"A loader specifically designed for this type of file is necessary," webpack is unable to interpret the angular2 file

I am encountering an issue while setting up a basic Angular2 app with Webpack as the module bundler. I am following the guidelines provided in this code repository and have configured all files accordingly, making necessary changes to file paths. However, ...

Ensuring uniqueness in an array using Typescript: allowing only one instance of a value

Is there a simple method to restrict an array to only contain one true value? For instance, if I have the following types: array: { value: boolean; label: string; }[]; I want to make sure that within this array, only one value can be set to t ...

Setting up OpenID configuration in angular-oauth2-oidc to bypass authentication for certain addresses

In my Angular project, I implemented OpenID authentication using the angular-oauth2-oidc project. However, I need to disable authentication for certain routes. To achieve this, I start the code flow in the main component and bootstrap it in the main modu ...

Is there a way to retrieve the headers from the error callback when using the subscribe function?

When a user creates a post, I need to handle any error responses from the server that may occur. The post creation occurs in the UserService's createUser() method. Any errors are caught using the catch method and a new error is thrown. It is important ...

Troubleshooting problems with resolving deeply nested promises

My approach to utilizing promises has been effective until now. The issue arises when the console.log(this.recipe) returns undefined and console.log(JSON.stringify(recipes)) displays an empty array. This suggests that the nested promises may not be resolvi ...

Validating Form Controls with Dynamic Names in Angular 5

Initially, I believed this task would be straightforward. The following snippet of HTML is functioning as anticipated: <label class="mb-0 form-label"> Doc Part </label> <input type="number" name="DocPart" #DocPart="ngModel" class="form- ...

There was an issue encountered while compiling the template for 'AppModule'

While attempting to construct an Angular 6 application, I encountered an issue when utilizing the --prod flag. ERROR in Error during template compile of 'AppModule' Expression form not supported in 'reducers' 'reducers' ...

The instanceof function provides an erroneous response when verifying a valid condition

SCENARIO // debugging Discord applications import { Client } from 'discord.js'; export class Debugger { constructor(public client: Client) { console.log(client instanceof Client); // outputs false } } // main.ts import { Client ...

Managing two subscriptions based on conditions in Angular

I'm currently working on a component that includes the following code snippet: this.service().subscribe((result) => { this.service2(result).subscribe((result2) => //other code }} As I strive to follow best practices in Angular development, I&ap ...

I am encountering an error where authManager is not defined

I am encountering difficulties with authentication through Auth0. An error message stating "authenticate is undefined on the authManager" keeps appearing. The authManager is supposed to be injected into the authService, and both are added in the app unde ...

Steps for positioning the date popup below the text field

My task in Angular 4 involves creating a date field that displays a date popup beneath it when clicked. See below for my code snippet: <div class="col-3"> <div class="form-group calenderForm calenderForm1"> <label for="templateName"& ...

Optimizing an ASP.NET web application for seamless integration with Angular 2 and TypeScript

For the past couple of days, I have been delving into angular2. I am curious to understand the process of configuring my project to effectively utilize angular2 and typescript. My development environment is Visual Studio 2015. Can you guide me on the nec ...