2

Is it necessary to map to labels and values in order to show values on dropdown ?

I'm trying to show enums on my dropdown but they are not displaying correctly !

  export enum nature
    {
        annuelle="Annuelle",
        semestrielle="Semestrielle",
        trimestrielle="Trimestrielle"

    }
 naturevalues = Object.values(nature);
 <div class="ui-grid-col-6">
                    <p-dropdown [options]="naturevalues"  formControlName="nature"></p-dropdown>
                </div>

this is the list I can see the chosen value on the console i can see the chosen value on the console I tried to add optionLabel="value" but in vain

1
  • you need to set like {label: '', value: ''}, Commented Jun 12, 2020 at 13:35

2 Answers 2

6

For those who come here from Google:

nature.enum.ts

export enum Nature {
   annuelle = "Annuelle",
   semestrielle = "Semestrielle",
   trimestrielle = "Trimestrielle"
}

In component.ts: define a list, where Nature is just an imported enum:

import {Nature} from 'enums/nature.enum';
//other imports

  public natures = Nature;

And in your template use keyvalue pipe and set optionLabel to value:

<div class="ui-grid-col-6">
    <p-dropdown [options]="natures | keyvalue" optionLabel="value" formControlName="nature"></p-dropdown>
</div>
3

Demo set to primeng options this

 naturevalues =   Object.keys(nature).map(key => ({ label: nature[key], value: key }));
3
  • but i don't want to turn my variable nature into an array of labels and values , i want to get the value directly like in the screenshot above , is it possible ?
    – Lamyae Lac
    Commented Jun 12, 2020 at 13:46
  • You can do it with custome template inside pdropdown Commented Jun 12, 2020 at 13:47
  • But in this situation you may have several problems such as to see selected item. So I suggest you to use label value and with onchange method assing your wanted output tipe with mapping. One single selected its output is string You can check in demo Commented Jun 12, 2020 at 14:09

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.