Modifying the property value based on the selected item from a dropdown menu in Angular 2

I am brand new to Angular 2 and I have come across the following code snippet.

<select name="shape_id" (change)="changeShape()">
    <option *ngFor="let shape of shapes" [ngValue]="shape.name">
      {{shape.name}}
    </option>
  </select>

When selecting an option from the dropdown, I would like to assign the selected shape ID to a property called shapeId in my component.

The available shapes are as follows:

[{"name":"aa","id":"1"},{"name":"bb","id":"3"},{"name":"cc","id":"2"}]

If anyone could assist me with this, it would be greatly appreciated.

Answer №1

This particular solution allows for the direct binding of the chosen object to a component property, giving flexibility to handle the selected shape in any way within the event handler.

Key Excerpts:

To begin, let's define the structure:

interface Shape {
  name: string;
  id: number;
}

Snippet of Template code:

<select (change)="changeShape()" [(ngModel)]="selectedShape">
  <option *ngFor="let shape of shapes" [ngValue]="shape">
    {{shape.name}}
  </option>
</select>
<p>Selected shape: {{shapeName}}</p>

Snippet of Component code:

private selectedShape: Shape;

private shapes : Shape[] = [
  {name: "circle", id: 0},
  {name: "rectangle", id: 1}
];

private shapeName: string;

public changeShape() {
  this.shapeName = this.selectedShape.name;
}

Answer №2

<select name="shape_id" (change)="handleChange($event.target.value)"> // incorporate this into the change method
    <option *ngFor="let shape of shapes" [ngValue]="shape.id">
      {{shape.name}}
    </option>
  </select>

In Component

selectedVal: string;

handleChange(selectedValue: string) {
    this.selectedVal = selectedValue;
}

You can also choose either option as they will both work

<select name="shape_id" [(ngModel)]="selectedItem"> // utilize ngModel in this case
    <option *ngFor="let shape of shapes" [ngValue]="shape.id">
      {{shape.name}}
    </option>
  </select>

The variable "selectedItem" will be within the Component

Update Post-Comment

<select name="shape_id" (change)="handleChange(i)"> // include this in the change method
    <option *ngFor="let shape of shapes; let i = index" [ngValue]="shape.id">
      {{shape.name}}
    </option>
  </select>

Pass the index value and then you can reference the id in the component to update "selected value" to "selected index: number"

Answer №3

when setting up your design -

<select name="form_id" (update)="updateDesign($event.target.value)">
  <option *ngFor="let form of forms" [value]="form.id">
    {{form.name}}
  </option>
</select>

within your element -

designId: string;

updateDesign(id: string) {
    this.designId = id;
  }

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

Error message: "Supabase connection is returning an undefined value

I am encountering an issue with my Vercel deployed Remix project that utilizes Supabase on the backend, Postgresql, and Prisma as the ORM. Despite setting up connection pooling and a direct connection to Supabase, I keep receiving the following error whene ...

Confirm your identity without using a Single Sign-On (SSO) system

My current situation involves a PHP-based website where users login using credentials stored in a database. Additionally, we have another SPA website with .NET CORE as the API layer. Unfortunately, we do not have the option of utilizing a central authent ...

The issue here pertains to npm's inability to successfully retrieve a required dependency for download

C:\Users\Manoj\Desktop\accounts>npm install intro.js --save npm ERR! code ENOENT npm ERR! syscall spawn git npm ERR! path git npm ERR! errno ENOENT npm ERR! enoent Error while executing: npm ERR! enoent undefined ls-remote -h -t ssh: ...

simulate the behavior of a promise function within a class

I'm facing an issue with this class structure: @Injectable() class ServiceOne { method1(): Promise<any>{ return new Promise((resolve,reject)=>{ // performing some operations let value = 1; resolve({'value':1}); }); } ...

Developing Angular components with nested routes and navigation menu

I have a unique application structure with different modules: /app /core /admin /authentication /wst The admin module is quite complex, featuring a sidebar, while the authentication module is simple with just a login screen. I want to dyn ...

Having trouble with CSS values not being applied to dynamically injected HTML div elements in Angular 4?

Link to Codepen My Angular calendar application runs smoothly without any errors. However, I am encountering an issue where the CSS styles are not being applied to the page. When I implemented this separately, everything worked fine. But as soon as I inc ...

The 'Headers' type does not share any properties with the 'RequestOptionsArgs' type

I have included the necessary headers, objects, and URLs in my code but I keep getting an error message. The 'Headers' type does not have any properties in common with the 'RequestOptionsArgs' type This is my code: getContactData(a ...

accessing observables programmatically in Angular 5 using a service getter

Assistance Needed with Service Component ... cart: any = {...}; //observable set in a subscription to an API response get Cart() { return this.cart; } ... Problem with Component Implementation get Cart() { return this.bcCartService.Cart; } constru ...

Obtaining the current row index in React MUI Data Grid using React-Context

Scenario In my application, I have implemented an MUI Data Grid with custom components in each row: RowSlider, RowDate, and RowLock using the MUI Components Slider, Date Picker, and Button respectively. View the Data Grid Visualization The Slider and Da ...

Troubleshooting login problems with MSAL and AD B2C

Despite dedicating a significant amount of time to learning and implementing MSAL, I am still facing challenges. Multiple issues have left me unsure of how to proceed or where I might be going wrong. Here is what I have accomplished so far: 1) Downloaded ...

Iterate through a collection of objects and organize the data in a specific way

Within the data structure of my API response, I am attempting to iterate through an array of objects under the items key. Each value inside these objects needs to be formatted based on the corresponding format type specified in the header key. To assist wi ...

Storing Data Locally in Angular with User Authentication

Using angular8, I encountered an issue where logging in with USER1 credentials, closing the browser, and then attempting to log in with USER2 credentials still logged me in as USER1. While adding code to the app component resolved this problem, I faced an ...

Angular - Implementing a debounce feature for event handling

Currently, I am utilizing the mouseenter and mouseleave events to control the opening and closing of my sidenav within the app. However, I have encountered issues because when hovering over the container quickly, these events are triggered multiple times ...

Error: The property 'process' cannot be read because it is not defined

Seeking help with a code issue Any advice on best practices would be greatly appreciated. Thank you! An error has occurred: TypeError: Cannot read property 'process' of undefined myComponent.ts ProcessInfo: any | false; showSaveItems = ...

Implementing dynamic data updates for the yAxis in a chart using Highcharts and Angular 2/4

I am currently working with a spline chart: this.chart = { chart: { type: 'spline', zoomType: 'x', animation: true, marginRight: 10, renderTo ...

Having difficulty handling the "of" class within the "rxjs" framework

I have created a custom class named ValueService. Here is the code snippet: import { Injectable } from '@angular/core'; import { of } from 'rxjs'; import { delay } from 'rxjs/operators'; @Injectable() export class ValueSer ...

Setting a default value and object ID in Angular's reactive forms for a select dropdown

Having an issue with validating a default value in a selector that serves as a message to select an option. The problem arises from the validation of this option, as it is linked to the object ID of another collection in the database (mongoose-express js). ...

Dayjs is failing to retrieve the current system time

Hey everyone, I'm facing an issue with using Dayjs() and format to retrieve the current time in a specific format while running my Cypress tests. Despite using the correct code, I keep getting an old timestamp as the output: const presentDateTime = da ...

When I executed the npm install -g @angularcli command, I encountered an npm error with the code ENOLOCAL

On my initial attempt, I used a computer with Windows 10 and another one with Windows 8.1. Surprisingly, I encountered the same error message on both systems. The log of the error is as follows: npm ERR! code ENOLOCAL npm ERR! Could not install from "@ang ...

Learn how to utilize React lazy effectively in components that utilize Redux compose without any similarities to type 'IntrinsicAttributes'

Here is the structure of a component that is exported with compose from redux. This component is called TestInspector.tsx export interface TestInspectorProps { closeInspector: () => void; onExpand: () => void; isFullScreen: boolean; selected ...