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

后端 未结 2 441
清酒与你
清酒与你 2021-01-04 03: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?

相关标签:
2条回答
  • 2021-01-04 03:25

    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>
    
    0 讨论(0)
  • 2021-01-04 03:35

    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;
      }
    
    }
    
    0 讨论(0)
提交回复
热议问题