[FIXED] Primeng p-dropdown onChange get value of the Object

Issue

I have a p-dropdown in which I want to get the value that is selected.

<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 tried using (ngModelChange) instead of (onChange) as well as trying $event, $event.target.value, $event.value for the parameter to getValue in my html. The console always prints [object Object].

My motivation for wanting to see the actual value is that I need the value to populate another dropdown. I use this value that I’m trying to see, as a search value to actually populate the other dropdown. This search keeps returning undefined.

Solution

To get the value of the first dropdown I didn’t need to use (onChange). Just base both dropdowns on the same value with [(ngModel)], but populate their options like I already was.

<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;

So what I needed was when I choose my name in the first dropdown, I need the second dropdown to populate with that names corresponding id. I was having trouble getting the name which is what my question here actually asks for. That was just part of this larger scheme of functionality that has now been solved.

Answered By – Drew13

Answer Checked By – David Goodson (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published