Tips for retrieving an item from a (dropdown) menu in Angular

I am facing an issue with selecting objects from a dropdown list. The array called "devices" stores a list of Bluetooth devices.

Here is the HTML code:

   <select (change)="selectDevice($event.target.data)">
          <option>Select device</option>
          <option *ngFor="let device of devices">
            Name: {{device.name}} -
            Address: {{device.address}} -
            Class: {{device.class}}
            <br>
          </option>
   </select>

In the TypeScript file:

  selectDevice(singleDevice: BluetoothDevice){
  console.log(singleDevice)
  }

This is the structure of the BluetoothDevice class:

export class BluetoothDevice {
public id: string
public class: number
public address: string
public name: string
}

I need help in obtaining the selected object instead of the string representation.

UPDATE: I attempted to use [(ngModel)] instead of (change), but when I log the object to the console, it displays as [object Object] instead of the actual selected object. Why is that happening?

Answer №1

If you want to retrieve the current value of a select element, follow these steps:

<!-- HTML TEMPLATE -->
<select [(ngModel)]="selectedDevice">
  <option [ngValue]="null">Select device</option>
  <option *ngFor="let device of devices" [ngValue]="device">
    Name: {{ device.name }} -
    Address: {{ device.address }} -
    Class: {{ device.class }}
    <br>
  </option>
</select>

Use

[(ngModel)]="selectedDevice"
to access the selected device from the select element.
Then utilize [ngValue] in the options to pass the selected object.

[value]="..." only works with string values
[ngValue]="..." supports any data type

In your Typescript file, create a property for the selectedDevice.

import { Component } from '@angular/core';
import { BluetoothDevice } from '@app-models/bluetooth-device'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {

  constructor() { }

  selectedDevice: BluetoothDevice | null = null;

}

Don't forget to include the FormsModule in the imports array of your working module.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms'; // Required for ngModel to function.
// Components
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
  ],
  declarations: [AppComponent],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule { }

You should now be all set. You can remove the selectDevice function and directly access the selected device by referencing the selectedDevice property.

import { Component } from '@angular/core';
import { BluetoothDevice } from '@app-models/bluetooth-device'

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {

  constructor() { }

  selectedDevice: BluetoothDevice | null = null;

  onSumbit() {
    if (!this.selectedDevice) {
      console.log('No device selected');
      return;
    }
    console.log('Device selected: ', this.selectedDevice);
  }

}

Answer №2

ts:

CurrentDevice:BluetoothDevice;

SetDevice(){
  console.log(this.CurrentDevice);
}

Html:

<select (change)="setDevice()" [(ngModel)]="CurrentDevice">
      <option>Select device</option>
      <option *ngFor="let device of devices" [ngValue]="device">
        Name: {{device.name}} -
        Address: {{device.address}} -
        Class: {{device.class}}
        <br>
      </option>
</select>

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

ng-module with tabbed content

I am facing a unique scenario where I have a UserProfileComponent with a tab structure and I want to add tabs from different modules. UserProfileComponent.html <ngb-tabset> <ngb-tab> <app-user-profile-history></app-user-prof ...

Unable to compile because error TS1039 prohibits initializers in ambient contexts

Upon updating my global Angular CLI to the latest version, I encountered an error. After some research, it seems that the issue may be related to my local CLI version (1.5.0) not being utilized for some reason. I am now unable to build the project due to t ...

Maintaining search filters across pages in Angular 2 using URL parameters

I am attempting to store certain filters in the URL for my application, so that they can be reapplied when the page is reloaded. I am encountering challenges with Dates (using moment), nullable properties, and special characters (/). When I pass values to ...

Sharing a variable between an Angular component and a service

I am attempting to pass a variable from a method to a service. from calibration-detail.component.ts private heroID: number; getTheHeroID() { this.heroService.getHero(this.hero.id).subscribe(data =>(this.heroID = data.id)); } to step.service.ts I ...

Storing JWT securely in cookie or local storage for a Node.js/Angular 2 web application

I've been researching how to save jwt tokens in either local storage or cookies but I'm having trouble finding clear instructions online. Can someone provide guidance on how to instruct the server to recognize a user for future sessions? //a ...

Using a memory cache in development with NextJS does not seem to be effective

When exporting my pages for my simple static blog site, everything runs smoothly and quickly. However, in development mode, the generation of posts is sluggish and I'm looking to implement caching to speed up the process. I have set up a file called p ...

The "fullName" input remains constant despite any changes made during text input

Currently, I am in the process of implementing a ControlValueAccessor in a child form. In my setup, there is a parent form group and control structured like this: this.form = this.formBuilder.group({ user: ['', Validators.required] ...

What is the process of combining two states in Angular?

Having a state defined as: export interface ChatMessagesState { messages: Message[] | null; chatId: string; } and receiving data in the websocket like: newMessages: Message[] = [ { text: 'Hello', chatId: '100' }, { text ...

Bind the change event of an Angular input to a variable that contains a custom function

Is there a way to achieve something similar to the following? <input (input)="doSomething($event)" /> <input (input)="boolVar = $event.target.value > 5" /> I would like to accomplish it by defining a function, like this: funcVar = (e) =&g ...

Guide to retrieving Response Header in Angular 8 when making a POST request

Looking to fetch the response Header in Angular 8 after a post request and securely store the jwt token in localstorage? login(req): Observable<any> { return this.http.post(this.apiUrl + '/login', req).pipe( map(res => { if ...

Nativescript encountered an error regarding faker: module './address' not found

Currently in the process of learning nativescript, I am experimenting with using faker to generate some data while working with typescript. Here are the versions I am using: Node - 6.9.4 Faker - 3.1.0 Typescript - 2.1.4 Encountered an error which i ...

Only apply patches to untouched values

Looking for a way to patch only the pristine properties of my reactive form in Angular. Received updates from a websocket service regarding user data, and want to update the form based on the payload without changing dirty properties. Below is the code s ...

Saving a JSON object to multiple JSON objects in TypeScript - The ultimate guide

Currently, I am receiving a JSON object named formDoc containing data from the backend. { "components": [ { "label": "Textfield1", "type": "textfield", "key": "textfield1", ...

Activate / Deactivate controls

My task involves creating a feature that displays multiple audio files, each with its own play button. When a specific button is clicked, the corresponding audio should play and the button should change to a stop icon. How can I manage the behavior of each ...

Angular error message: Trying to access the property 'name' of an undefined object leads to a TypeError

I'm having trouble phrasing this question differently, but I am seeking assistance in comprehending how to address this issue. The error message I am encountering is as follows: TypeError: _co.create is not a function TypeError: Cannot read property ...

Achieve the capability to upload multiple files in Next.js using the upload.io integration feature

I'm currently using upload.io for uploads and replicate.com for an AI model on a specific app. I am able to upload one picture, but unfortunately, I am encountering issues when trying to upload multiple pictures. Can anyone identify the problem here? ...

Exploring cutting-edge Angular 2 UI controls?

Imagine this scenario: An extensive organization is in need of developing a large web application with advanced UI components, such as hierarchical grid/tree and charts, alongside the standard UI elements. All these controls should ideally be sourced fro ...

Warnings when compiling Angular with declarations of Angular Material components

Recently, I've been encountering numerous warnings during compilation after installing Angular Material. The warnings persist whether I install it directly from npm or through ng add @angular/material, regardless of whether I opt to use animations or ...

Is there a way for me to retrieve the bodyHeight attribute of ag-grid using public variables or data?

Working on a project using ag-grid community react. The main feature is a scrollable section filled with data, which can range from one piece to millions of pieces. I'm also incorporating a footer component for the grid that needs to adjust its height ...

What could be preventing the array from updating after subscribing to the service?

Attempting to fetch a list of movies from a Web API server on my localhost. The server does provide data when called with a Get request using the HttpClient module, but struggling to display it. MovieList Component import { Component, OnInit } from &apos ...