Change the name of the dropdown menu according to selection in Angular

随声附和 提交于 2021-02-11 14:27:57

问题


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

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