Retrieving the Object value in Primeng p-dropdown when there is a change in selection

In my p-dropdown, I am trying to extract the selected value.

<p-dropdown optionLabel="name" [options]="things"
                  placeholder="Select Thing" [(ngModel)]="input" (onChange)="getValue(input)"></p-dropdown>

typescript:

//each line prints the same thing of [object Object].
getValue(changedValue){
    console.log(changedValue);
    console.log(this.input);
    console.log(this.input.valueOf());
}

I have also experimented with using (ngModelChange) instead of (onChange) and attempting $event, $event.target.value, $event.value as parameters for getValue in my html. However, the console consistently displays [object Object].

The reason behind my quest to retrieve the actual value is that I require it to populate another dropdown list. The value I'm attempting to retrieve serves as a search keyword to populate the new dropdown. Unfortunately, this search keeps resulting in undefined.

Answer №1

In order to retrieve the value from the initial dropdown, I found that utilizing (onChange) was not necessary. Instead, I simply linked both dropdowns to the same value using [(ngModel)], while still populating their options as before.

<p-dropdown optionLabel="name" [options]="things"
                  placeholder="Select Name" [(ngModel)]="input"></p-dropdown>

<p-dropdown optionLabel="id" [options]="things"
                  placeholder="Select ID" [(ngModel)]="input"></p-dropdown>

ts:

things: Thing[];
input: String;

This is what things looks like:

things = [
        {id: 20, name: 'First'},
        {id: 45, name: 'Second'},
        {id: 22, name: 'Third'},
        {id: 67, name: 'Fourth'},
        {id: 88, name: 'Fifth'}
];

type Thing:

id: number;
name: string;

Essentially, when selecting a name in the first dropdown, I required the second dropdown to display the corresponding id for that chosen name. Initially, my struggle was centered around retrieving the appropriate name, which was the focal point of my inquiry here. Thankfully, this challenge has now been successfully resolved within the broader functionality framework.

Answer №2

If you want to make your things array compatible with ng prime's dropdown expectations, you should format it as shown below:

interface City {
  name: string;
  code: string;
}

selectedCity1: City;

this.cities1 = [
            {label:'Select City', value:null},
            {label:'New York', value:{id:1, name: 'New York', code: 'NY'}},
            {label:'Rome', value:{id:2, name: 'Rome', code: 'RM'}},
            {label:'London', value:{id:3, name: 'London', code: 'LDN'}},
            {label:'Istanbul', value:{id:4, name: 'Istanbul', code: 'IST'}},
            {label:'Paris', value:{id:5, name: 'Paris', code: 'PRS'}}
        ];
<p-dropdown [options]="cities1" [(ngModel)]="selectedCity1"></p-dropdown>

Explore more examples here

Answer №3

This method worked successfully for me

In my project, I used a dropdown component with the following syntax: <p-dropdown [options]="projectData" [(ngModel)]="selectedProject" (onChange)="onProjectChange($event)" optionLabel="ProjectName" id="project" name="project" placeholder="Select Project">

Within my code, I declared a variable named selectedProject of type any and defined a function called onProjectChange to handle changes:

selectedProject: any; onProjectChange(e:any){

this.selectedProject = e.target.value; }

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

Trouble with 'import type' declaration causing build issues in a Next.js project

Having trouble importing the Metadata type from the next module. The code snippet below is directly from the Next.js documentation. THE ISSUE client.js:1 ./app/layout.tsx:3:12 Syntax error: Unexpected token, expected "from" 1 | import React from 'r ...

Angular application experiencing issues with loading React web component: encountering error when attempting to search for 'adoptedCallback' using 'in' operator with undefined value

I recently created a basic web component using React import React from "react"; import ReactDOM from "react-dom/client"; import reactToWebComponent from 'react-to-webcomponent'; function Test() { return ( <h1> He ...

Implementing Angular 4 on a Node Express server within Firebase platform

After setting up an angular 4 project using angular cli, I decided to incorporate express into my application. I created a file named app.js with the following content: app.js const express = require('express') const app = express() ...

Tips for developing a collaborative service for utilization across numerous Angular applications

Is it feasible to develop a shared service that can be utilized in numerous Angular applications? And if so, how? For instance, similar to how we create an Angular library that can be accessed externally by packaging it into an npm package. Is it possible ...

Updating the latest version of Typescript from NPM is proving to be a challenge

Today, my goal was to update Typescript to a newer version on this machine as the current one installed is 1.0.3.0 (checked using the command tsc --v). After entering npm install -g typescript@latest, I received the following output: %APPDATA%\npm&b ...

What role does the @Input statement in the HeroDetailComponent class serve in the Angular 2 Quickstart tutorial?

Looking at the multiple components part of the Angular 2 Quickstart tutorial, we see how a component is separated from the AppComponent to enhance reusability and testing convenience. You can try out the example live demo here. In this scenario, users ar ...

Creating an object instance in Angular 2 using TypeScript

Looking for guidance on creating a new instance in TypeScript. I seem to have everything set up correctly, but encountering an issue. export class User implements IUser { public id: number; public username: string; public firstname: string; ...

The process of adding new files to an event's index

I'm trying to attach a file to an event like this: event.target.files[0]=newFile; The error I'm getting is "Failed to set an indexed property on 'FileList': Index property setter is not supported." Is there an alternative solution fo ...

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

Update constant data returned from Angular2 service

Issue at Hand: I am facing an issue where I want to store default data in a separate file so that I can easily reset the default value when needed. However, the Const Data seems to be getting updated. I could simply hardcode the value directly into the co ...

Trouble with Firebase Setup in Ionic 4+ Web Application

I'm currently trying to establish a connection between my ionic application and Firebase for data storage, retrieval, and authentication. Despite using the npm package with npm install firebase, I encountered an error message that reads: > [email& ...

"Linking a Next.js application with Azure's Application Insights for advanced insights

Trying to include my Next.js (TypeScript) app logs in Azure Application Insights has been a bit challenging. The documentation provided poor guidance, so I decided to follow this solution: https://medium.com/@nirbhayluthra/integrating-azure-application-ins ...

Switch over to TypeScript - combining Socket.IO, Angular, and Node.js

This is the code I'm using for my node server: import http from 'http'; import Debug from 'debug'; import socketio, { Server } from 'socket.io'; import app from './app'; import ServerGlobal from './serve ...

Unable to pass a parameter through an Angular http.get request

I've encountered an issue where I am attempting to pass the page number and page size values to a web API, but for some reason, no parameters are being passed. I have thoroughly debugged the application in VS Code, and verified that the pagingModel ob ...

The Formik and React error is indicating that the '{ refetch: any; }' type is absent

When attempting to pass a prop down to my EmailSignupScreen, I encountered an error message. This issue arose while experimenting with Formik and Typescript. "message": "Type '{ refetch: any; }' is missing the following properties from type &apo ...

Timestamps are no longer recognized in Highstock charts once data has been added

In my highstock chart, I am pulling data from a REST api and everything appears correct. However, there is no data available between 19:00 and 05:00. I would like this absence of data to be reflected in the chart without cropping out that time span from th ...

Guide to dynamically updating image URLs based on color selection in Angular when handling ngFor loop

component.ts // necessary imports have been included ngOnInit() { this.list = { 'eatList': [{ 'class': 'Fruits', 'color': ['Red', 'White', 'Black& ...

Setting up TypeScript compilation for TS modules in an AngularJs application: A comprehensive guide

After conducting a test, it has come to my attention that TypeScript 2.6.2 imposes a requirement where imported elements need to be used in a new before the module is referenced in a require. The test is based on the following code snippets extracted from ...

Issue with Angular 6 subscribe event not being caught by subject?

A new element was crafted to house a loader: @Component({ selector: 'app-loader', templateUrl: './loader.component.html', styleUrls: ['./loader.component.scss'], providers: [LoaderService] }) export class LoaderCompon ...

I'm curious about the type I can set for the first parameter of setState in TypeScript. Is there a way to pass a dynamically generated state object to setState?

When trying to pass a newState object to setState and add some additional properties under certain conditions, I encountered a type error: I attempted to define the new State as Pick<ItemListState, keyof ItemListState> but received a type error ...