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

Ionic 2 fails to navigate when using [navPush]

Today I delved into working with Ionic 2 and was making good progress. I had successfully implemented navigation across 3-4 pages, but then something suddenly broke that has left me scratching my head. Now whenever I try to navigate to another page, I kee ...

The firebase-generated observable is causing the notorious differ error as it is not iterable

Hey there, I'm encountering an issue that's preventing the route from rendering correctly. I initially thought that unwrapping an observable into an iterable using the async pipe would solve it, but this error indicates otherwise. Sometimes obser ...

Unlocking the power of variables in Next.js inline sass styles

Is there a way to utilize SASS variables in inline styles? export default function (): JSX.Element { return ( <MainLayout title={title} robots={false}> <nav> <a href="href">Title</a> ...

Verify if Angular 2 route parameters have a legitimate value

Within an angular2 component, I have the following code: ngOnInit() { this.route.params .switchMap((params: Params) => this.elementsService.getElement(+params['id'])) .subscribe(element => { this.elementToEd ...

Mastering Inter-Composable Communication in Vue 3: A Guide

Composables in Vue documentation demonstrate how small composition functions can be used for organizing code by composing the app. Discover More About Extracting Composables for Code Organization "Extracted composables act as component-scoped servi ...

Organize an array based on its ratio

I am attempting to organize an array based on the win and lose ratio of each player. This is how my code currently looks: const array = [{playerName: 'toto', win: 2, lose: 2}, {playerName: 'titi', win: 0, lose: 0}, {playerName: &apo ...

Determine the data type of a parameter by referencing a prior parameter

Consider a scenario in my software where I have two distinct implementations of an Event Emitter. For instance: type HandlerA = (data: boolean) => void; type HandlerB = (data: number) => void; // HandlerB is somehow different from HandlerA type Eve ...

The inversify middleware is executed a single time

I utilize Inversify for object binding in the following manner: container.applyMiddleware(loggerMiddleware); let module = new ContainerModule((bind: interfaces.Bind) => { bind<Logger>(TYPES.Logger).toConstantValue(logger); bind<ILogger ...

Struggling to incorporate method decorators to handle http errors in Angular?

My goal is to implement error handling for all http requests using custom decorators. Here's my current code snippet: createRecord(data: data) { return this.httpClient.post(`${this.apiURL}/record/`, data); } I am looking to refactor thes ...

Unable to modify the theme provider in Styled Components

Currently, I am attempting to customize the interface of the PancakeSwap exchange by forking it from GitHub. However, I have encountered difficulties in modifying not only the header nav panel but also around 80% of the other React TypeScript components. ...

Utilize dynamically generated form fields to upload multiple files at once

Currently, as I delve into learning the MEAN stack, I am encountering difficulties with file uploads. Specifically, within a company form: this.companyForm = this.fb.group({ trucks: this.fb.array([]), ... }); The 'trucks' field i ...

Obtain a personalized response from an Angular HTTP service

I'm trying to implement the following code directly in a component: if(exampleService.checkValidityOfToken()) { //do something } Here is the method in exampleService that corresponds to this. I'm not sure if I am returning the value properly or ...

Is it possible to send a single backend request to serve multiple endpoints?

http://examplewebsite.com/product-list?gender=2&category=4 http://examplewebsite.com/product-list?gender=2 http://examplewebsite.com/product-list?category=4 I am looking to consolidate these endpoints into one backend controller. Is it possible to a ...

Using Angular to call a separate function from within a click event handler within the same function itself

It seems like the issue at hand is related to the keyword "this" not being assigned as expected. I am currently using Angular 5 along with a WordCloud package. You can find more information about it here. There's a click callback function that retur ...

Converting a "String" value to a specific "Type" in Angular 2 using TypeScript

This is my current object, Home points to the import statement for Home component. import { Home } from '../home/home'; arr = [ { name: "Home", root: Home, icon: "calc" } ]; This is what I want to achieve: import { Home } from & ...

Struggling to implement the Pick utility type alongside the React useState hook

Can anyone explain why I am unable to utilize the Pick utility type in order to select a property from my interface and apply it to type my component's state? This is what my interface looks like: export interface IBooking { ... propertyId: strin ...

Modify the parent property's value within a derived Angular service

I'm utilizing Angular 9 and I have Service A along with Service B which extends Service A. Within Service A, there's a specific property that I aim to modify its value from within Service B. Surprisingly, the change only reflects in Service B and ...

Angular's Reactive forms: The power of bidirectional binding

Struggling with Reactive forms? I've encountered an issue where updating the model class when a User changes the input is easy, but what about programmatically changing the model and reflecting those changes in the HTML form? In simplified terms: th ...

Sending information from a component to a route in Angular2

Is it possible to transfer data from one component to another without displaying it in the URL during routing? Currently, I am passing data using route parameters like this: { path: 'edit-tags/:type/:name/:id', component: EditTagsCompon ...

Incorporate a JavaScript library into a personalized JavaScript file that is utilized within my Angular2 project

Integrating Machine Learning into my Angular2 project using the "synaptic.js" JavaScript library is my goal. After executing the command npm install synaptic --save I intend to execute a custom javascript file (myJsFile.js): function myFunction() { v ...