Issue with <select> tag in angular5

Issue

I am facing an issue with <select> tag in angular 5. I have an array of objects. Lets say

public countryList = [ {
    'name': 'xxx',
    'capital': 'abc'
  }, {
    'name': 'yyy',
    'capital': 'efg'
  }, {
    'name': 'zzz',
    'capital': 'pqr'
  },
];

and in html

    <select placeholder="Select" (change)="displayFunction()">
              <option class="auto-height" *ngFor="let country of countryList; let id=index"
                [disabled]="id === (country .length)-1" [value]="country .name">
                <div class="stop-container">
                    <b>{{country.name}}</b>
                    <p>{{country.capital}}</p>
               </div>
      </option>

The issue comes when we select any option in the dropdown all the values listed inside<option> is shown as the slected value. I need only name as selected value. Any solution for this? I am getting output given below. What is need is XXX instead of XXX abc

enter image description here

Solution

You can’t have a div inside your option. If you want to have some special formatting inside a dropdown you have to recreate the dropdown with JS (or use, for example, angular material)

So to only display the name, you can do the following:

<select placeholder="Select" (change)="displayFunction()">
      <option class="auto-height" *ngFor="let country of countryList; let id=index"
                [disabled]="id === (country .length)-1" [value]="country .name">
                {{country.name}}
      </option>
</select>

Answered By – cloned

Answer Checked By – Candace Johnson (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.