John
John

Reputation: 207

Show value of option when chosen on select in Angular

I'm a newbie in Angular. I have a problem with select tag. I have a list country name and country code. When I chosen an option, I want the result on the select show only country code(value of option) instead of country name and country code. Example:

<select>
  <option value="+1">USA: +1</option>
  <option value="+66">THA: +66</option>
  <option value="+56">CHL: +56</option>
  <option value="+84">VN: +84</option>
</select>

When I select the USA, select tag will show "USA: +1" on screen, but I want to only show "+1" in this.

enter image description here

Have any solutions for this case? If yes, please send me any example code. Thanks so much!

Upvotes: 1

Views: 119

Answers (2)

Martin Parenteau
Martin Parenteau

Reputation: 73791

In the markup, you can define a hidden first option with the default selected value, and set a handler for the (change) event:

<select (change)="onSelectChange($event)">
  <option hidden value="+1">+1</option>
  <option value="+1">USA: +1</option>
  <option value="+66">THA: +66</option>
  <option value="+56">CHL: +56</option>
  <option value="+84">VN: +84</option>
</select>

Every time an option is selected:

  • The value of the hidden option is set to the selected value
  • The text of the hidden option is set to the selected value
  • The hidden option is selected
onSelectChange(event: Event) {
  let select = event.target as HTMLSelectElement;
  select.options[0].value = select.value;
  select.options[0].text = select.value;
  select.selectedIndex = 0;
}

See this stackblitz for a demo.

Upvotes: 1

Raman0716
Raman0716

Reputation: 1

I tried a demo like this:

<select (click)="status=!0" (mouseout)="status=!1" style="width:120px">
    <option value="+1">{{status ? 'USA: ' : ''}}+1</option>
    <option value="+66">{{status ? 'THA: ' : ''}}+66</option>
    <option value="+56">{{status ? 'CHL: ' : ''}}+56</option>
    <option value="+84">{{status ? 'VN: ' : ''}}+84</option>
</select>

u can make it better

Upvotes: 0

Related Questions