Tutorials on transferring selected option data to a component

My JSON data is structured like this:

Whenever I choose an option, I want to pass the values (code and description) from the JSON object to the component.

nameList= [
  {
    "code": "1",
    "description": "abc"
  },
  {
    "code": "123",
    "description": "def"
  },
  {
    "code": "100",
    "description": "ijk"
  }
]

Below is the HTML code:

<select [(ngModel)]="description" #category="ngModel" aria-required
 (change)="getNameList()"> //want to send data.code value to component
    <option style="display:none"></option>
    <option *ngFor="let data of nameList"> {{data.description}} 
    </option>
</select>

Check out the demo here

Answer №1

For optimal results, implement the following code snippet: [ngValue]="data"

 <option *ngFor="let data of nameList" [ngValue]="data"> {{data.description}} 
 </option>

Upon implementation, access the component as follows:

  getNameList() {
     console.log(this.description);
  }

Experience a LIVE DEMO on StackBlitz

Answer №2

If you want to enhance your TypeScript code, consider utilizing interfaces. Here's an example of how your HTML could look:

<hello name="{{exampleSelected?.description}}"></hello>

<select [(ngModel)]="exampleSelected" aria-required (change)="getNameList()">
    <option style="display:none"></option>
    <option *ngFor="let data of nameList" [ngValue]="data"> {{data.description}} 
 </option>
</select>

As for your TypeScript code:

import { Component } from '@angular/core';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})


export class AppComponent {
  exampleSelected;

  nameList = [
    {
      "code": "1",
      "description": "abc"
    },
    {
      "code": "1",
      "description": "def"
    },
    {
      "code": "1",
      "description": "ijk"
    }
  ]

  getNameList() {
    console.log(this.exampleSelected);
  }
}

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

Executing a TypeScript function directly in HTML without the need for a click event

I understand how to trigger a TypeScript function when clicking a button, but how can I initiate a function without relying on a specific event? My goal is to call a function once an array named chartData has been populated. Here is the code snippet I have ...

What is the location to enter the function I wish to execute in Bootstrap JavaScript?

I need help implementing the following JavaScript code into my web app to ensure that all fields are filled out before allowing the information to be processed. Where and how should I include the function to check if all fields are populated? // Here is ...

The Eclipse Phonegap framework is experiencing difficulty in loading an external string file with the jquery .load function

A basic index.html file has been created to showcase a text string from the test.txt file by utilizing the .load function from the jQuery library. The goal is to insert the textual content into an HTML (div class="konten"). The provided HTML script looks ...

Guide on utilizing map function and reassigning the value

I am facing a challenge with a list of books that have IsEnable defaulting to False. During onInit(), I need to check each book to see if it is enabled. I was considering using an rxjs map and calling the getEligibleBooks() function within the map, but I ...

How can I silence the warnings about "defaultProps will be removed"?

I currently have a next.js codebase that is experiencing various bugs that require attention. The console is currently displaying the following warnings: Warning: ArrowLeftInline: Support for defaultProps will be removed from function components in a futur ...

release a Node.js module on NPM

Being a complete beginner in creating npm packages using typescript2 and angular2, I find myself in need of creating an npm package and publishing it on our company's private repository. I've managed to generate files like d.ts and .js. But how ...

Setting a default year in a React datepicker: A step-by-step guide

I'm currently working with the react datepicker and I want to specify a default year (1990) when the calendar is opened. I've tried using the 'date' and 'initialDate' props, but they don't seem to be working. Below is th ...

Implementing Angular's Lazy loading feature can be achieved by loading a module within another module that has

In my Angular application, the main routing module successfully lazy loads modules. However, I now have a new requirement to include another component/module inside one of the lazy loaded modules. When navigating to users/id (which is working correctly), ...

Include specific javascript files only for smartphones

Recently, I encountered an issue with a JavaScript code that swaps background images on scroll down. To address the problem with debounce, I ended up setting different debounce times for various browsers (I am aware this is not the ideal solution, but it&a ...

What is your approach to organizing the HTTP requests in your Angular 2+ application?

I'm looking for suggestions on how to better organize my API calls within my services. How have you structured your API calls? Do you centralize all API calls for the entire application in one dedicated service? Do you create an HTTP folder and sepa ...

Encountering problem with image file encoding while using res.download in Express.js

My node.js server with expressjs is set up for local development, where I store and retrieve various files through basic HTTP calls. Most of the time, everything works smoothly. However, on rare occasions, a small number of files return to the end-user sig ...

Ways to modify the color of mat-icon within an input field using Angular 6

Here is the code from my HTML file: <div class="input-field"> <div> <input type="text" id="name" required email/> <label for="name">Email: <mat-icon svgIcon="mail" class="change-color"></mat-icon> &l ...

Is Angular9 BehaviorSubject from rxjs giving trouble across different components?

I am facing an issue with updating data in real-time from the profile component to the header component. Initially, it works fine but after updating any value in the profile component, the header observable does not subscribe again. To solve this problem, ...

Difficulty encountered when applying date filtering on a specific filter in the MUI-DataGrid

Software Version: "@mui/x-data-grid": "^6.2.1" I have a script that generates columns for the DataGrid as shown below (only including relevant code) if (prop === "date" || prop === "dateModified" || prop === "n ...

Using Knex to Generate a Migration Including a Foreign Key

I attempted to use the code from this link in order to create a foreign key: how to do knex.js migration However, an error occurred at this line of code: table.bigInteger('AddressId') .unsigned() .index() .inTable('Address&apos ...

Develop a built-in Button for Liking posts

Currently, I am encountering an issue with the JavaScript SDK where I am unable to create a built-in Like button. After researching, I came across this helpful resource: https://developers.facebook.com/docs/opengraph/actions/builtin/likes/ The solution pr ...

Updating API calls with form submission in React.js

Currently working on a weather application and attempting to update my API call upon submitting a form. This project marks my initial attempt at developing my own program, and I've encountered an obstacle. The plan is for the user to input a city, cli ...

Creating a variable amount of datasets depending on database values in an easy way

I am striving to create a dynamic graph in PHP using CanvasJS with multiple datasets generated based on values from a database. Generating the graph with only one dataset was successful, but making it "dynamic" has proven to be a challenge. For a single d ...

Learn the process of eliminating special characters from input or textarea fields with AngularJs!

My attempts to integrate an AngularJS directive to remove special characters from input and textarea fields have been unsuccessful. Despite no errors being reported in the console, I am facing issues with the character count tooltip not displaying numbers ...

Exploring the ins and outs of data exchange within Angular 2

I'm currently in the process of developing an angular2 application. One of the components in my project is the MountainListComponent, which is composed of other components (although this detail is not crucial) and is nested within a parent component. ...