问题
There is this dropdown menu in my Angular web-application:
<div class="btn-group" dropdown>
<button dropdownToggle type="button" class="btn btn-primary dropdown-toggle">NAMEOFDROPDOWN
<span class="caret"></span></button>
<ul *dropdownMenu class="dropdown-menu" role="menu">
<li role="menuitem"><a class="dropdown-item" routerLink="/first">First</a></li>
<li role="menuitem"><a class="dropdown-item" routerLink="/second">Second</a></li>
<li role="menuitem"><a class="dropdown-item" routerLink="/third">Third</a></li>
</ul>
</div>
I want the name of the Dropdown, where currently reads NAMEOFDROPDOWN, to change to whatever is the name of the route that I select from the dropdown.
How do I do this?
回答1:
Bind a click
event to the list elements like:
<li role="menuitem"><a class="dropdown-item" routerLink="/first" (click)="changeRoute('First')">First</a></li>
<li role="menuitem"><a class="dropdown-item" routerLink="/second" (click)="changeRoute('Second')">Second</a></li>
<li role="menuitem"><a class="dropdown-item" routerLink="/third" (click)="changeRoute('Third')">Third</a></li>
Then in your component's .ts
-file you define a method changeRoute(route)
which set's an attribute selectedRoute
.
export class YourComponent {
selectedRoute = "default value";
changeRoute(route: string) {
this.selectedRoute = route;
}
}
and finally you bind the value of your dropdown button to this attribute:
<button dropdownToggle type="button" class="btn btn-primary dropdown-toggle">
{{selectedRoute}}
<span class="caret"></span></button>
来源:https://stackoverflow.com/questions/60028972/change-the-name-of-the-dropdown-menu-according-to-selection-in-angular