Choosing from a list in Angular

I'm trying to make a dropdown menu that shows options in the format "code-description", but only displays the "code" portion when an option is selected. For example, showing "A-Apple" in the dropdown, but displaying only "A" when chosen. I am able to pass the value as just the code, but struggling to display it as the code alone in the selected field.

Answer №1

According to AhmerMH, providing more precise details and sharing some code along with other information would be beneficial.

The type of drop-down menu you require and the structure of your data play a significant role in implementation. Here are some example snippets that might assist you:

  1. If you need a drop-down menu similar to mat-menu and your data is organized in lists, you can utilize the following approach:
Drop Down Codes and Descriptions option 2 option 3 option 4
<mat-menu #moreOptions="matMenu">
    //it depends on how the objects you want to display are made 
    //if code and description are in the same object:
    <div *ngFor="let c of codesList; index as i">
        <button mat-menu-item>{{c.code}} {{c.description}}</button>
    </div>

    //otherwise, if code and description are separated: (if codes are in "codesList" and descriptions are in "descsList" and if descsList is ordered in the same way of codesList)
    <div *ngFor="let c of codesList; index as i"> 
        <button mat-menu-item>{{c}} {{descsList[i]}}</button>
    </div>

</mat-menu>
  1. In case you are looking for a form-field type drop-down, there are various scenarios depending on your data:

2.1 - If you have a set amount of fixed data points, consider using this method:

<div class="row">
    <div class="col">
        <mat-form-field class="" appearance="outline" floatLabel="always" hideRequiredMarker>
            <mat-label>Codes and Descriptions</mat-label>
            <mat-select formControlName="data" (selectionChange)="doSomething()">
                <mat-option *ngFor="let d of referenceData" [value]="d.value">
                    {{d.code}} {{d.description}}
                </mat-option>
            </mat-select>
        </mat-form-field>
    </div>
</div>

To correspondingly define it in your .TS file, use:

form = this.fb.group({
    data: [''],
})

And include the list of data like so:

referenceData = [
{code: 'Code One', description: 'Desc One', value: 'first_value'},
{code: 'Code Two', description: 'Desc Two', value: 'second_value'},
{code: 'Code Three', description: 'Desc Three', value: 'third_value'},
]

2.2 - If your data varies and needs to be fetched from a database:

<div class="row">
    <div class="col">
        <mat-form-field class="" appearance="outline" hideRequiredMarker formGroupName="data" *ngIf="data$ | async as datas"> 
            <mat-label class="font-18-semi-b">Codes and Descriptions</mat-label>
            <input matInput formControlName="id" placeholder="Data">
            <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayData(datas)" (optionSelected)="dataChanged($event.option.value)">
                <mat-option *ngFor="let d of datas" [value]="d.id">
                    {{d.code}} {{d.description}}
                </mat-option>
            </mat-autocomplete>
        </mat-form-field>
    </div>
</div>

In your .TS file:

form = this.fb.group({
    data: this.fb.group({
        id: ['',],
      }),
})

data$: Observable<Data>;

displayData(datas: Data[]) {   
    return (dataId?: number): string | undefined => {
      let data = datas.find(option => option.id === dataId);
      return data ? data.code + " " + data.description : undefined
    };
}
  
dataChanged(event){
    this.dataService.get(event).pipe( //your service that you use to get the data from the server
      tap((value:Data) => {
        //do what you want, like:
        var selectedData = value; 
      })
    ).subscribe();
    this.form.get("data.id").setValue(event);
} 

I hope this provides some assistance :)

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

Adding rows dynamically to multiple tables on a single page using a single function

I am facing a situation where I have multiple tables and a function that adds rows to these tables: <table id="table1" style=" border-collapse: collapse;"> <tr id="table1row1">... <tr id="table1row2">... <table id="table2" style=" bor ...

What causes the Material-UI Grid element to shift upon clicking it?

I have encountered an issue while developing a React app with Material UI. The problem arises on a specific page of the application. This particular page consists of text and a button aligned vertically, along with a second set of text and another button ...

Monitoring WooCommerce order submissions through AJAX

I'm exploring the world of Ajax for the first time. My goal is to submit an order tracking form and show the results using AJAX. I attempted to use Ajax to display the results within div track_result. The issue I'm facing is that the following ...

Update the referenced lists in ng-admin

I'm currently working with ng-admin alongside a restful API, I have various referenced lists that undergo frequent updates from the server side. Is there a method to automatically refresh these referenced lists every 5 seconds using ng-admin? EDIT: ...

Is there an issue with the jQuery ajax function when it comes to sending the RegistrationId to our server?

Beginning to work with the pushNotification service for my Android app, I successfully received a registration ID from the GCM server and attempted to send this ID to our server using a jQuery AJAX function. My intention was to send this ID after the user ...

Creating a customizable filter by using the function of an object

I am currently developing a customizable dynamic filter system, similar to the functionalities offered by Yahoo Screener. To achieve this, I have defined an interface for the available filter fields: export interface FilterField { label: string; se ...

The function Observable.timer in Angular rxjs is throwing an error when imported

Encountering an error in my Angular application that reads: ERROR TypeError: rxjs_Observable__WEBPACK_IMPORTED_MODULE_4__.Observable.timer is not a function at SwitchMapSubscriber.project (hybrid.effect.ts:20) at SwitchMapSubscriber.push ...

I'm currently working on incorporating a rating system into my Vue.js project, but I am struggling to successfully pass the rating values

After carefully reviewing the documentation, I implemented the code below. While I am successfully retrieving data for enquiryDesc, I am encountering null values for rating. Despite trying various troubleshooting steps, the issue with null values persists. ...

Cross-browser compatibility issues preventing CSS button effects from functioning properly

Experiencing some challenges with CSS Button effects not functioning consistently across different browsers. The display is satisfactory in Chrome, but not in Firefox. Struggling to pinpoint the source of the issue. Here is my current setup: Fiddle a ...

Unable to install npm package from git source

I am attempting to install a package from a git repository that I had previously forked. Here is the command I tried: npm i catsaredoomed/invest-openapi-js-sdk --save-dev Unfortunately, I encountered this error message: npm ERR! prepareGitDep 2> npm W ...

How can I apply a blurred effect to the background image of a jumbotron in Bootstrap-vue without affecting the clarity of the text overlay

I need help figuring out how to blur the background image of my jumbotron without blurring the text on top. <b-container fluid class="text-center"> <div> <b-jumbotron class="jumbotron"> <p style=& ...

Mastering the Art of Line Breaks in WordPress

I am looking for a way to break a WordPress site title over two lines at a specific point in the text. Since the WordPress content filter 'wpautop' disables the ` ` tag (also known as ` ` or ` `), I'm wondering what the best alternative ...

Utilizing a navigation menu to display various Strapi Collection pages within a single Angular Component

I have set up a collection in Strapi called Pages and I am looking to display them in the same component using my Navigation Bar Component. However, I am unsure of how to achieve this. Currently, all the data from the Collection is being displayed like th ...

Verify if the JSON response contains any data

When the JSON response is empty and viewed in the browser console, it appears like this: {"data":{},"status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://url/form/BN217473" ...

Navigating PopUpWindows using SeleniumIn this guide, learn the best

I have attempted to manage a particular PopUp / new Window in Java using SeleniumServer, but unfortunately, it is not functioning as expected. Here is what I have tried: selenium.click("css=a[title=\"Some irrelevant title\"] > div.text"); Thr ...

In Safari, my layout is disrupted by the mere mention of the word 'City'

There's something strange happening in Safari that I can't quite figure out. Here's how my layout looks in Chrome: https://i.sstatic.net/lPhnP.png But when viewed in Safari, it looks like this: https://i.sstatic.net/IMnQb.png For some r ...

Whenever the page is refreshed, the props in my application are dynamically updated thanks to the getStaticProps function I utilize

Currently, I am in the process of learning nextjs as a beginner. Through the utilization of the getStaticProps function, I have come to understand that data fetching occurs only once at build time and the values remain static thereafter. Despite this, I ...

When the object contains multiple arrays, filter out the id and remove it when clicked

I am working with an object that contains multiple arrays and aiming to filter out the id of the item to be removed onClick. However, I have encountered an error while trying to implement this logic. The error message I received is filter is not a functio ...

Stack screen not visible on React Native navigation

I'm currently utilizing the React Native Navigation library for routing. However, I've encountered an issue with the code below that doesn't seem to be functioning as expected. My objective is to set up two screens - one for login and the o ...