What is the best way to fetch the chosen item in an Angular select dropdown

I am working on a dropdown that populates with items of type ObjectA.

item.component.html:

<label>items list:
    <select formControlName="itemsCtl" (change)="onChange()">
        <option *ngFor="let item of itemList" [value]="item">{{item.label}}</option>
    </select>
</label>

When using reactive forms, I require the selected item. After researching extensively, I found suitable code for my requirement:

item.component.ts:

selectedItem : ObjectA;
...
onChange()
{  
    this.selectedItem = this.factorForm.controls['itemsCtl'].value;
}

However, upon retrieving the selected item, it is displayed as [object object] instead of as ObjectA. How can I ensure that the selected item is returned as ObjectA, or how can I convert [object object] to ObjectA?

This project is built using Angular version 5.0.1.

Answer №1

Consider implementing the ngValue directive instead of using the value attribute.

    <option  *ngFor="let item of itemList"  [ngValue]="item"   >{{item.label}}</option>

Answer №2

It seems like there may be some uncertainty regarding the structure of your (itemList) or your (ObjectA).

In order to provide a more accurate solution, I would require additional information.

If your current method is not yielding desired results, you can attempt the following approach:

<label>items list:
<select formControlName="itemsCtl" (change)="onChange()" [(ngModel)]="someVar">
    <option *ngFor="let item of itemList" [value]="item">{{item.label}}</option>
</select>

Next, in your function:

selectedItem : ObjectA;
someVar: any;
...
onChange()
{  
    this.selectedItem = this.factorForm.controls['itemsCtl'].value;
    console.log(someVar);
}

Observe the output generated by this code snippet.

I hope that these suggestions prove helpful!

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

Generating a custom type in Typescript based on specific array keys

Imagine I have a structure like this: export interface MyObject { id: number title: string } and then I create an array as shown below: const myArray: MyObject[] = [ { id: 2358, title: 'Item 1' }, { id: 85373, title: &a ...

Working with Vue class-based components in TypeScript and setting props

Currently tackling a typescript-related issue within a class-based component and seeking guidance on a persistent error. Below is the code snippet for my component: <template> <b-message :type="statusToBuefyClass"> <p>PLACEHOLDER& ...

Automatically closing the AppDateTimePicker modal in Vuexy theme after selecting a date

I am currently developing a Vue.js application using the Vuexy theme. One issue I have encountered is with a datetimepicker within a modal. The problem arises when I try to select a date on the datetimepicker component - it closes the modal instead of stay ...

What makes TS unsafe when using unary arithmetic operations, while remaining safe in binary operations?

When it comes to arithmetic, there is a certain truth that holds: if 'a' is any positive real number, then: -a = a*(-1) The Typescript compiler appears to have trouble reproducing arithmetic rules in a type-safe manner. For example: (I) Workin ...

Sending information to custom components in Angular2 Smart Tables

Incorporating Angular2, I am currently working on implementing a view link for each row within my Smart Table using the custom type to render a personalized component. Although the rendering process is functioning properly, I am faced with the challenge o ...

React TypeScript throws an error when a Socket.IO object is passed to a child component and appears as undefined

Currently, I'm developing a simple chat application as part of my university course. The code below represents a work-in-progress page for this project. While I am able to get the socket from the server and use it in the main component without any is ...

Attempting to grasp Angular through an online tutorial - currently facing challenges with understanding ViewContainerRef and TemplateRef

I have been successfully learning Angular until I reached the topic of structural directives. In order to understand them, I had to create my own using TemplateRef and ViewContainerRef. The instructor in the course demonstrated it this way: import { Direc ...

utilizing props to create a navigational link

How can I display a tsx component on a new tab and pass props into the new page? Essentially, I'm looking for the equivalent of this Flutter code: Navigator.push( context, MaterialPageRoute(builder: (context) => Page({title: example, desc: ...

Tips for executing forEach on a promise?

I am currently working with a function that returns a promise of an array: async function functionReturningPromiseOfUserIDs(): Promise<string[]> My question is, can I use the forEach method on the array returned by this function? async function runF ...

Error: The 'update' property cannot be found on the specified type

Starting a new AngularCli project and need to incorporate a Gauge chart. I've used the code from StackBlitz Angular Gauge Chart Example When I run ng serve --open, I encounter the following errors in the terminal: ERROR in src/app/gauge/gauge.comp ...

Uncertainty surrounding refinement in Typescript

I've been diving into the book Programming TypeScript, and I'm currently stuck on understanding the concept of refinement as shown in this example: type UserTextEvent = { value: string; target: HTMLInputElement }; type UserMouseEvent = { value: [ ...

Is it possible for a React selector to retrieve a particular data type?

As a newcomer to React and Typescript, I am currently exploring whether a selector can be configured to return a custom type. Below is a basic selector that returns a user of type Map<string, any>: selectors/user.ts import { createSelector } from ...

Importing from source code instead of a file in TypeScript: How to do it

I found this code snippet to help with dynamic component loading: loadComponent(name) { var url = this.configurationService.configuration.api_url+"/generator/dynamic-loading/component/"+name; this.http.get(url, {responseType: 'text'}). ...

Custom generator designed for projects with tailored ng/nrwl versions

Unfortunately, due to various reasons, we are unable to utilize angular version 12 at this time. As a result, we do not wish to use the current versions of ng and nrwl. I have been unable to find any documentation on how to generate a project with a speci ...

Showing a notification in Angular 4 following a background request

In my page, I have a list of posts that display comments when clicked. Everything is working well, but now I want to show a message if there are no comments for the selected post. Here's how I tried setting up the template: <li *ngFor="let post of ...

Exploring Aurelia's Integration with ASP.NET Core Models

Recently, I've been delving into various JavaScript frameworks and made the decision to rework an ASP.Net Core MVC frontend using Aurelia. To kick things off, I utilized the SPA template. Everything has been smooth sailing so far - I’ve integrated ...

Tips for sorting through the properties of the Record<K, T>:

Let's say we have the following data stored in a record: export const MenuData: Record<Header, HeaderInfo> = { val1: { message: 'xyz', buttonText: 'txt', buttonUrl: '/url-abc', }, val2: { messa ...

Function is not triggered in React component

When the LoginPage calls AuthForm, the structure is as follows: function mapDispatchToProps(dispatch: Redux.Dispatch<any>) { return { signUpWithEmail: function(email: string, password: string) { // bla bla }, }; } handleForm ...

Utilizing Regular Expressions in Angular 4 by Referencing Patterns Stored in an Object

I'm facing an issue where my code is functional, but I keep encountering a Tslint error that's proving difficult to resolve. This particular configuration worked fine with Angular 1, but now I'm in the process of migrating the application to ...

Unable to resolve host name for registry.npmjs.org on port 80

Hello everyone! I'm currently working on getting my angular library published on npm, but I seem to be running into an issue. When I try to log in, I encounter the following error: npm ERR! code EAI_AGAIN npm ERR! errno EAI_AGAIN npm ERR! request to h ...