How to configure NgbDropdown to display the selected item from the dropdown

TrumanCode picture TrumanCode · Feb 11, 2017 · Viewed 37.6k times · Source

In ng-bootstrap NgbDropdown, how would you display the text of the selected button so that what ever item the user selects replaces the default text initially shown?

In the example below, the goal is to display whatever sorting option the user selects.

<div ngbDropdown class="d-inline-block">

  <button class="btn btn-outline-primary" id="sortMenu" ngbDropdownToggle>Sort by...</button>

  <div class="dropdown-menu" aria-labelledby="sortMenu">
    <button class="dropdown-item">Year</button>
    <button class="dropdown-item">Title</button>
    <button class="dropdown-item">Author</button>
  </div>

</div>

Thanks for your help!

Answer

Rob Mullins picture Rob Mullins · Feb 11, 2017

Demonstrated in this plunkr.

Example Component:

import {Component} from '@angular/core';

@Component({
  selector: 'dropdown-demo-sortby',
  template: `
    <div ngbDropdown class="d-inline-block">
      <button class="btn btn-outline-primary" id="sortMenu" ngbDropdownToggle>{{selectedSortOrder}}</button>
      <div class="dropdown-menu" aria-labelledby="sortMenu">
        <button class="dropdown-item" *ngFor="let sortOrder of sortOrders" (click)="ChangeSortOrder(sortOrder)" >{{sortOrder}}</button>
      </div>
    </div>
  `
})
export class DropdownDemoSortby {

  sortOrders: string[] = ["Year", "Title", "Author"];
  selectedSortOrder: string = "Sort by...";

  ChangeSortOrder(newSortOrder: string) { 
    this.selectedSortOrder = newSortOrder;
  }

}