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

After executing "npm run dev" in Svelte and Vite, a common error message of "HTMLElement is not defined" might appear

Incorporating several web components into my Svelte project led to the appearance of an error message stating HTMLElement is not defined after running npm run dev (which actually translates to vite dev). The complete error message reads as follows: HTMLEl ...

Do not generate authentication code in JHipster using the --skip-server flag

Is there a reason why the authentication part is lost when generating a project with '--skip-server'? yo jhipster --skip-server It seems that upon generating the project without the server, the authentication gets affected (on AJS/A2). Is thi ...

Angular compilation error: unexpected ng target

Recently, my Angular code started throwing an "Invalid ng target" error on a blank page after being built and deployed to the IIS server. I'm unable to pinpoint what has changed in my code. I typically use multiple environment files, and this issue is ...

Exploring the Uses of SystemJS with TypeScript Loader

Can someone help clarify something about this TypeScript plugin for SystemJS? https://github.com/frankwallis/plugin-typescript/ Here is what the plugin does: This SystemJS plugin allows you to import TypeScript files directly and have them compiled in ...

Is it possible to overlook TypeScript errors when compiling with Angular 2 AoT?

My application is experiencing numerous TypeScript errors, even though it runs correctly. I recently migrated a JavaScript app to TypeScript and am struggling to resolve all the type-related issues. In order to proceed with development, I have configured m ...

"Triggering a click event on the unordered list within an Angular 2

Looking to retrieve the class name when clicking on any item in a list. <ul id='color' name='color' class="choose-color" (click)=getColor()> <li class="color1"></li> <li class="color2"&g ...

Passing the output of ComponentA as the input for ComponentB in Angular

I have just started learning Angular and one strategy I find helpful is to work on small projects. Currently, I am focusing on 3 components, but for now, only two are relevant: TANavBarComponent TAPageContainerComponent Within my TANavBarComponent, I aim ...

Refreshing a component without having to reload the entire page in Angular4: A step-by-step guide

I have an application built with Angular 4 that consists of two components - one for adding items and another for viewing them. I am facing an issue where the view page does not update with the new item added. Although I can see the updated data source, th ...

Expanding TypographyProps and TextFieldProps for enhanced functionality

Currently, I am developing a React component using TypeScript along with Material UI (MUI). The main purpose of this component is to display either an input field or text based on the mode selected. To switch between these modes, the prop mode is utilize ...

Separate HTTP responses into multiple Observables

I need assistance in splitting a HTTP response into different Variables/Observables. The returned data is in JSON format: [ { "status": [ { "id": 1, "value": "active"}, { "id": 2, "value": "inactive"} ] }, { "type": [ ...

Angular 2 approach to retrieving items from an Observable<Xyz[]>

After reviewing the Typescript code in an Angular 2 service: getLanguages () { return this.http.get(this._languagesUrl) .map(res => <Language[]> res.json().data) .catch(this.handleError); I'm encountering a challenge whe ...

Tips for accessing web API within an Angular service

Just starting out with angular and in need of some guidance on how to call my API within the angular code. Can anyone provide assistance? The API I am using is: [HttpGet,Route("api/customer/getCustomer/{name}")] public async Task<IHttpActionResult> ...

Exploring child components through auxiliary routing in Angular

After defining the root routing as shown below: const routes: Routes = [{ path: '', component: HomeComponent }, { path: 'module1', loadChildren: './module1/module1.module#Module1Module' }, { path ...

The installation of bower angular-card-input failed during the execution of the Jenkins build script due to an HTTP request

I encountered an issue when trying to run a bower script for building a frontend in Angular: When executing the bower command, I received an error regarding git fetch from the following link: https://github.com/angular-ui/ui-utils.git, with exit code ...

Loading a large quantity of items into state in React Context using Typescript

I am currently working on a React context where I need to bulk load items into the state rather than loading one item at a time using a reducer. The issue lies in the Provider initialization section of the code, specifically in handling the api fetch call ...

The specified path "/src/app/app.module.ts" was not found while attempting to add ng in an Angular project that is using a custom path

I encountered an issue while attempting to integrate Angular Universal into my project. Here is my folder structure: src main app app.module.ts node_modules tsconfig.json My project uses Angular version 15.2.5 and the latest version of Angular Uni ...

Angular Recurring Request

Currently, I am using Angular5 and making requests every 5 seconds to check the status of a task. However, I would like to implement a more flexible condition where if the request receives a status code of 202, continue sending requests, but if it receives ...

Angular framework does not trigger the button click event

Currently, I am in the process of creating a web app and working on designing the register page. My experience with Angular is still at a beginner level. The following code snippet is from the resiger.component.ts file: /** * To create a new User ...

Struggling to implement mock JSON data, unable to dynamically update on HTML page

Although the data is being displayed, I am facing issues with getting the images to appear correctly based on the syntax and code. <h2>Amazing Places on Earth</h2> <div class="card"> <div class=" card-block"> <im ...

Encountering Compilation Error When Using RxJS Observable with Angular 6 and Swagger Codegen

Encountering TypeScript compiler errors related to rxjs while working with Angular 6 and Swagger Codegen: Cannot find module 'rxjs-compat/Observable' Referenced the following link for assistance: https://github.com/ReactiveX/rxjs/blob/master/M ...