Why does clicked item not getting selected on dropdown instead it always shows title text

Viewed 168

My dropdown always shows the title text on it Select Location not showing selected item even though the click event working.

This is .html file

<div ngbDropdown class="d-inline-block">
 <button class="btn btn-secondary btn-sm dropdown-toggle" id="dropdownMap" ngbDropdownToggle>Select Location</button>                
   <div ngbDrop4downMenu aria-labelledby="dropdownMap">

    <button class="dropdown-item" *ngFor="let country of countries" 
    (click)="mapCountry_selected(country)" >{{country}}</button>      
 </div>

</div>

Code in .ts file

public mapCountry_selected(country)
 {
   var c=country;
 }
1 Answers

In order to display the selected item country, you have to fake the label you are displaying.

You can have a variable selectedCountry which will display either the selected country or the default value "Select Location"

The templating

<div ngbDropdown class="d-inline-block">
 <button class="btn btn-secondary btn-sm dropdown-toggle" id="dropdownMap" ngbDropdownToggle>{{selectedCountry}}</button>                
   <div ngbDrop4downMenu aria-labelledby="dropdownMap">

    <button class="dropdown-item" *ngFor="let country of countries" (click)="mapCountry_selected(country)" >{{country}}</button>      
 </div>

</div>

and the .ts code

  countries = ["Country 1", "Country 2", "Country 3"];
  selectedCountry = 'Select Location'

  mapCountry_selected(country) {
    this.selectedCountry = country
  }
Related