Accessing a specific value based on a selected option in Angular 2+

Examining the Angular 2+ code snippet below, there is an Array defined in TypeScript:

models = [{idModele: 1, model: "Bianca", price: 500}, {idModele: 2, model: "etc", price: 600} ] 

The query here is about setting up a mechanism where selecting a specific model would dynamically display its price within a < p > tag or similar element.

An illustration using HTML Example:

 <select class="form-control" id="modeles" formControlName="modeles">
                    <option selected>Choisir...</option>
                    <option *ngFor="let modele of modeles">{{ modele.modele }}</option>
 </select>

Answer №1

If you want to achieve this task effortlessly:

Simply include the following code in your app.component.ts:

export class AppComponent  {
  selectedPrice:Number
  models:Array<Object> = [
      {idModele: 1, model: "Bianca", price: 500}, 
      {idModele: 2, model: "etc", price: 600} 
  ] 
}

Next, add the given code snippet in your app.component.html:

<h1>Selecting Model</h1>
<select [(ngModel)]="selectedPrice">
  <option *ngFor="let model of models" [ngValue]="model.price">
    {{model.model}}
  </option>
</select>

<hr>

<p>{{ selectedPrice }}</p>

Answer №2

Take a look at the code snippet below.

HTML Code:

    <select class="form-control" id="options" [(ngModel)]="selectedItem">
    <option *ngFor="let option of optionsList" [value]="option.price">{{ option.name }}</option>
</select>

<p>{{selectedItem}}</p>

Typescript Code:

 selectedItem: number;
  optionsList = [
    { id: 1, name: "Option 1", price: 100 },
    { id: 2, name: "Option 2", price: 200 }
  ];

https://example.com/img.png

Answer №3

Here is a solution to try out:

If you're working in HTML:

<select . . .  [(ngModel)]="selectedValue"> 
    <option *ngFor="let model of models" [value]="model?.price">{{model.name}}</option> 
</select> 

{{selectedValue}}

And if you're working in TypeScript:

selectedValue: number;
  models = [
    { idModele: 1, name: "Bianca", price: 500 },
    { idModele: 2, name: "etc", price: 600 }
  ];

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

"Encountering issues with jQuery Ajax: Dealing with HTTP 405 or

When accessing a web service using jQuery Ajax that uses .asmx, I am encountering HTTP 405 and sometimes 500 errors. Is this a problem with the web service or on the client side? Please provide guidance with an example. $j.ajax({ type: ...

Should we opt for Controlled components or Uncontrolled components when it comes to working with HTML forms in React

I am currently faced with a decision on where the best location is for housing my Form State. The React documentation states: Identify every component that renders something based on that state.  Find a common owner component (a single component above ...

Building Custom Request Types for a Personalized Express Router in TypeScript (TS2769)

I've been facing challenges integrating custom Request types with TypeScript. Within my application, I have both public and private routes. The public routes utilize the Request type from Express. On the other hand, the private routes make use of a ...

Is it possible to perform a legitimate POST request using AJAX XMLHttpRequest, rather than the traditional var=val URL type post?

Apologies for the unclear question, but here is my query... I recently began using Ajax and encountered an issue with sending XMLHttpRequest in the background. I am facing problems with certain html special characters in the form data, especially the & ...

Choose your options effortlessly with CSS or JavaScript dropdown menus

As a novice web developer, I am contemplating whether dropdown menus are more suitable to be coded in CSS or JavaScript. What are the advantages and disadvantages of each approach? ...

Show complete items in Vue.js

Issue at hand: I am in need of displaying and potentially changing JSON data. My goal is to present it in a directory tree format. The structure of the object is unknown, it could be something like this: "buttons": { "login": "LOGIN", "register": ...

Is there an issue with the newline character ` ` not functioning properly in TypeScript when used with the `<br/>` tag?

Having trouble with using New Line '\n' ' ' in Typescript Here is an example of my typescript code: this.custPartyAddress = estimation.partyName + ',' + '\n' + estimation.partyAddress + ',' + ...

Having trouble importing the obj loader library in three.js

Attempting to load a 3D object into three.js, I decided to start with the very first basic example in the documentation since I am new to this. Everything seemed fine until I added the import line according to the documentation; suddenly, the scene disappe ...

Passing a variable to a template in Node.js and express with hbs is causing an unexpected identifier error

I’m working on a Node.js Express app, and I’m trying to pass a variable when rendering my index.hbs file, like this: <!DOCTYPE html> <html> <body> Hello. <a href="/auth/facebook">Login with Facebook</a> {{ ...

Issue with ExtJs 4 Grid panel resizing incorrectly when window is resized

I have a Grid Panel rendered in a DIV without specifying any width for either the DIV or the Grid Panel. I want them to take up all available browser width, but the Grid does not resize itself when the browser window is resized by the user. I have tried va ...

Retrieve all the data enclosed within the span tags

Assuming there are two instances of tbody on a given page, is it possible to retrieve all the data enclosed within the spans of the second occurrence of tbody as shown below? The unique id's (id=id1, id=id2, etc) can only be found once throughout the ...

What is the best method for organizing data in rows and columns?

I attempted to use my map function to iterate over the data and display it, but I struggled to format it into rows and columns. The requirement is for 5 fixed columns with dynamically changing rows, making array indexing impractical. Here is the code snip ...

Omit modules from the ng-bootstrap package when working with Angular 2

Is it possible to import specific components from the ng-bootstrap module into Angular 2? Currently, I have a custom tabset created using an existing ng-bootstrap component. However, upon importing ng-bootstrap, I am encountering a module duplication erro ...

Dealing with timeouts in getJSON requests

When using the jQuery getJSON() function, data is retrieved smoothly most of the time. However, there are instances where the loading process seems to be stuck, displaying "loading loading loadin" at the center of the page. While the ajax() function has ...

Utilizing the PATCH method with Dropwizard to remove a designated item from a list that is a part of another list

Currently, I am working on developing a PATCH API method that can remove a specific element from a list of items. This list of items is an integral part of the Menu class in my project. Unfortunately, there is a scarcity of Dropwizard resources available o ...

Error: Query is not valid

I'm encountering an error when trying to run this query, and I'm not sure why it's returning a bad request. My goal is to fetch a specific user from the database using the accountId. Can someone assist me with this issue? Below is the funct ...

What is the process for setting up custom global interfaces in TypeScript using .d.ts files?

I'm currently facing an issue in my ReactJS project using Webpack2 and TypeScript. Everything is functioning perfectly except for one thing - I've been struggling to move my self-written interfaces into separate files so they are accessible throu ...

Utilize the express library (NodeJS, TypeScript) to send back the results of my function

I am curious about how I can handle the return values of my functions in my replies. In this specific scenario, I am interested in returning any validator errors in my response if they exist. Take a look at my SqlCompanyRepository.ts: async create(compan ...

What is the best way to change a blob into a base64 format using Node.js with TypeScript?

When making an internal call to a MicroService in Node.js with TypeScript, I am receiving a blob image as the response. My goal is to convert this blob image into Base64 format so that I can use it to display it within an EJS image tag. I attempted to ach ...

Identifying the moment when a user deselects an option in mat-autocomplete

I am looking for a way to update other form fields based on the value of an autocomplete selection. To achieve this, I have implemented the optionSelected event handler: <mat-autocomplete (optionSelected)="onOptionSelected($event)"> <mat-opt ...