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

99封情书 提交于 2019-12-04 00:23:06

问题


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!


回答1:


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;
  }

}



回答2:


I solved this by hooking into the on-click event of the selected button ( using the blur event doesn't work in Firefox) - Plunkr demo

The component:

export class NgbdDropdownBasic {
    displayMessage = "Sort by...";
    sortOptions = ["Balance", "Company", "Last Name"]

    changeMessage(selectedItem: string){
       this.displayMessage = "Sort by " + selectedItem;
     }
 }

The template with NgbDropdown:

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

    <button class="btn btn-outline-primary"
            id="dropdownMenu1"
            ngbDropdownToggle >

    {{displayMessage}}

    </button>

    <div class="dropdown-menu" id="options" aria-labelledby="dropdownMenu1">
      <div *ngFor="let option of sortOptions">
        <button class="dropdown-item" 
                id="option" on-click="changeMessage(option)">{{option}}</button>

      </div>
    </div>
  </div>


来源:https://stackoverflow.com/questions/42170566/how-to-configure-ngbdropdown-to-display-the-selected-item-from-the-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!