PrimeVue Dropdown access country code from #value template to set default selected flag

49 views Asked by At

I have a Dropdown in a student edit modal, and need to show a flag for the default country. In PrimeVue the country code can be accessed from a template with #option="slotProps", but not with #value="slotProps". In that case i can only access the name of the country, and it will show the name of the country but not the flag. The slotProps.value.code?.toLowerCase() will be empty because there is no code but only an object with a value which is the country name and a placeholder that says select a country. And somehow i need to access the country code in order for the flag image to show.

    <div :class="flexBetweenCenter" class="mb-3 p-2">
      <label for="placeOfBirth">Place of birth</label>

      <Dropdown
        id="placeOfBirth"
        :options="countries"
        filter
        placeholder="Select a Country"
        v-model="user.placeOfBirth"
        optionLabel="name" 
      >
        <template #value="slotProps">
          <div v-if="slotProps.value" :class="flexAllignCenter">
            <img
              :alt="slotProps.value.label"
              src="https://primefaces.org/cdn/primevue/images/flag/flag_placeholder.png"
              :class="`me-2 flag flag-${slotProps.value.code?.toLowerCase()}`"
              style="width: 18px"
            />
            <div>{{ slotProps.value }}</div>
          </div>
          <span v-else>
            {{ slotProps.placeholder }}
          </span>
        </template>
        <template #option="slotProps">
          <div :class="flexAllignCenter">
            <img
              :alt="slotProps.option.label"
              src="https://primefaces.org/cdn/primevue/images/flag/flag_placeholder.png"
              :class="`me-2 flag flag-${slotProps.option.code?.toLowerCase()}`"
              style="width: 18px"
            />
            <div>{{ slotProps.option.name }}</div>
          </div>
        </template>
      </Dropdown>
1

There are 1 answers

1
Yong Lee On

Check this example https://stackblitz.com/edit/j8jihs?file=src%2FApp.vue

Your code seems to work fine provided that you have correct format for countries data.

countries: [
  { name: "United States", code: "US" },
  { name: "Canada", code: "CA" },
],

Screenshot of working example