在ng-bootstrap NgbDropdown中,您将如何显示所选按钮的文本,以便用户选择的项目替换最初显示的默认文本?
在下面的示例中,目标是显示用户选择的任何排序选项。
<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>
感谢您的帮助!
答案 0 :(得分:16)
在this plunkr中展示。
示例组件:
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;
}
}
答案 1 :(得分:1)
我通过勾选所选按钮的点击事件解决了这个问题(使用模糊事件在Firefox中不起作用) - Plunkr demo
组件:
export class NgbdDropdownBasic {
displayMessage = "Sort by...";
sortOptions = ["Balance", "Company", "Last Name"]
changeMessage(selectedItem: string){
this.displayMessage = "Sort by " + selectedItem;
}
}
带有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>
答案 2 :(得分:0)
我一直在与 ngbDropdown
斗争。我看到了这个博客并分配了。但它没有用。
过了一会儿,我找到了解决办法。我使用了 class="dropdown-menu"
指令而不是 ngbDropdownMenu
。代码如下。
import {Component} from '@angular/core';
@Component({
selector: 'dropdown-demo-sortby',
template: `
<div ngbDropdown class="d-inline-block">
<button class="btn btn-outline-primary" ngbDropdownToggle>
{{selectedSortOrder}}</button>
<div ngbDropdownMenu>
<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;
}
}
感谢您的阅读。