"Learn how to utilize Angular to showcase an array of strings and choose a specific value for

When working in HTML, I have the ability to set the option text and send the value like this:

<select id="cars">
 <option value="volvo">Volvo</option>
 <option value="saab">Saab</option>    
</select>

After sending it to my TS file, I can retrieve the value.

In Angular, I handle it like this:

<select  formControlName="Cars">
            <option *ngFor="let item of values_Car">
            {{item}}
            </option>
        </select>

TS

values_car : any = ["Volvo", "Saab"];

I am wondering how I can create a dictionary to display only the text and retrieve the corresponding values.

Answer №1

It seems like there is some confusion regarding the dictionary question, but you were on the right track with the *ngFor directive:

One thing to note is that you were not using the correct variable name values_car. Also, to bind the value correctly, you should use brackets around it, otherwise, "item" will be treated as a string instead of the actual value of the let item.

Here is the TypeScript code:

export class Car { 
    brand: string;
    id: string;
    constructor(brand: string, id: string) {
        this.brand= brand;
        this.id = id;
    }
}

values_car : any = [new Car('Volvo', '1'), new Car('Saab', '2')];

HTML code:

<select  formControlName="Cars">
    <option *ngFor="let item of values_car" [value]="item.id">
        {{ item.brand }}
    </option>
</select>

As you mentioned about an enum, I have included a function that converts an enum to an object to match the HTML structure.

carEnum: CarEnum = CarEnum

ngOnInit() {
    this.values_car = Object.keys(CarEnum).map(key => {
        return new Car(key, CarEnum[key])
    });
}

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

Guide to generating TypeScript output files within a non-hierarchical directory layout

In my project, I have a directory structure with multiple typescript files organized as follows: | src | app-1 | tsconfig.json | app-2 | tsconfig.json | common | standalone | tsconfig.json For each of the ...

What is the best way to integrate Sass into a Create-React-App project that is using TypeScript

After setting up a new project using create-react-app and typescript, I included a sass file in my project as per the documentation (which mentioned built-in support for sass files). However, when trying to compile, I encountered the following error relate ...

Dealing with server-side errors while utilizing react-query and formik

This login page utilizes formik and I am encountering some issues: const handleLogin = () => { const login = useLoginMutation(); return ( <div> <Formik initialValues={{ email: "", password: "" }} ...

The ReactJS Material Table Tree mode experiences delays when new row data is introduced

My Reactjs app utilizes the material-table widget within a component: render() { return ( <div> <Row> <MaterialTable title="Mon équipement" style={{ width: "100%", margin: "0%" }} ...

Making a HTTP Get request for a single item in Ionic 2

I have successfully implemented an API to retrieve data and display it on the page. It works perfectly for a json response containing more than one object, as it follows a "matches" hierarchy. However, I am facing an issue when trying to print out data for ...

The function item$.take cannot be found, resulting in a TypeError: "item$.take is not a function"

I am currently facing an issue with the take(1) function not working as expected with my Angular Firebase object. I have tried using valuechanges and snapshotchanges as alternatives, but they do not solve the problem for me due to other issues I encounter. ...

Having trouble resolving React within the Formik/dist package due to a custom webpack configuration

Struggling to set up projects from scratch, encountering an issue with webpack not being able to resolve formik's modules while other third-party modules like styled-components work fine. I've tried searching online for a solution but couldn&apos ...

Can we securely retrieve nested properties from an object using an array of keys in TypeScript? Is there a method to accomplish this in a manner that is type-safe and easily combinable?

I wish to create a function that retrieves a value from an object using an array of property keys. Here's an example implementation: function getValue<O, K extends ObjKeys<O>>(obj: O, keys: K): ObjVal<O,K> { let out = obj; for (c ...

Error encountered during npm installation - EPERM: Operation not allowed

Today's challenge began when attempting to run the angular4 project and encountering this error: npm install eperm operation not permitted. In an effort to resolve it, I decided to delete the node modules folder and try again. However, upon running np ...

What could be causing the error in Angular 2 when using multiple conditions with ng-if?

My aim is to validate if the length of events is 0 and the length of the term is greater than 2 using the code below: <li class="more-result" *ngIf="events?.length == 0 && term.value.length > 2"> <span class="tab-content- ...

Leveraging private members in Typescript with Module Augmentation

Recently, I delved into the concept of Module Augmentation in Typescript. My goal was to create a module that could inject a method into an object prototype (specifically a class) from another module upon import. Here is the structure of my folders: . ├ ...

When the next() function of bcrypt.hash() is called, it does not activate the save method in mongoose

Attempting to hash a password using the .pre() hook: import * as bcrypt from 'bcrypt'; // "bcrypt": "^1.0.2" (<any>mongoose).Promise = require('bluebird'); const user_schema = new Schema({ email: { type: String, required: tru ...

Demonstrating a feature in a custom Angular Material dialog box

I have a reusable custom Material UI Dialog that I want to utilize to show different components. For instance, I would like to display a Login component on one occasion and a Registration component on another. However, the issue arises when I assign my com ...

Show the subscription response data in Angular

When utilizing the code snippets below from two different components, I am able to receive a valid response value from the subscriber. dataService.ts fetchFormData(){ return this.http.get('http://localhost:48116/RecuruitmentService.asmx/addRoleTest ...

Using Ionic to send email verification via Firebase

I have encountered an issue while attempting to send an email verification to users upon signing up. Even though the user is successfully added to Firebase, the email verification is not being sent out. Upon checking the console for errors, I found the f ...

The functionality of TypeScript's instanceof operator may fail when the method argument is not a simple object

There seems to be an issue with a method that is being called from two different places but returns false for both argument types. Despite checking for the correct types, the problem persists and I am unsure why. Although I have read a similar question on ...

Navigating with Angular 6 - Utilizing Query Parameters within a designated secondary router outlet

Is it feasible to implement query parameters within a secondary named router outlet in Angular 6? An illustration of the desired URL format is localhost:4200/home(sidebar:chat?animal=dog) I aspire to set the query parameter "animal" and retrieve its valu ...

Steps for styling the header of an Antd Collapse Panel

I'm attempting to modify the text color in the header of an ant panel. Below is the entire ant collapse component code: <Collapse accordion defaultActiveKey={defaultOpenPanel}> <StyledCollapsePanel key="tasksAssignedToMe" header={ ...

How can I showcase images from a server in Node.js to an Angular 2 application?

I am currently facing an issue while trying to display uploaded files from Angular 2 using ngx-uploader and storing them on the backend (nodejs/feathers) with multer. I am unable to access and display the files, specifically images for now, but ultimately ...

Special Syntax for Defining Custom Record Keys in TypeScript

In the process of creating a small library, I am focused on enhancing type safety for the following object: export const ErrorCodeMap: Record<string, [string, number]> = { NOT_FOUND: ['1001', 222], ALREADY_EXISTS: ['1002', 111 ...