Skip to main content

Angular: Get Button Name

When building navigation, or handling button clicks, it’s sometimes necessary to retrieve the name of a button (or other control) from the click event. This is done by drilling into the MouseEvent that is passed into the handler.

Basically, we get the target property of the MouseEvent, cast it as an HTMLElement, and get the innerHTML string, which should be the button name.

For example, the following menu selections use the same click handler method:

    <clr-vertical-nav [clrVerticalNavCollapsible]="true">
        <a clrVerticalNavLink (click)="onSideMenuClick($event)" routerLinkActive="active">
            <cds-icon clrVerticalNavIcon shape="bolt"></cds-icon>
            RFI
        </a>
        <a clrVerticalNavLink (click)="onSideMenuClick($event)" routerLinkActive="active">
            <cds-icon clrVerticalNavIcon shape="sad-face"></cds-icon>
            Action Items
        </a>
        <a clrVerticalNavLink (click)="onSideMenuClick($event)" routerLinkActive="active">
            <cds-icon clrVerticalNavIcon shape="bug"></cds-icon>
            Issues
        </a>
    </clr-vertical-nav>

The above three menu selections all have a click event tied to the same handler method (onSideMenuClick).
This method call, determines which item was clicked, by interrogating the click event. See below:

  onSideMenuClick(event: MouseEvent) {
    // Get the name of the button that was clicked...
    var sss = (event.target as HTMLElement).innerHTML;

    // Open the desired page...
    switch (sss.trim()) {
      case "Action Items":
        this.openActionItemsPage();
        break;
      case "Return to Projects":
        this.NavigateToProjectsListing();
        break;
      case "RFI":
        this.openRFIPage();
        break;
        default:
        console.error("ProjectFrameComponent-" + this.instanceId + ":onMenuDropdownClick - encountered unknown dropdown button: " + sss);
        break;
    }
  }

The above click handler, accepts a MouseEvent, gets the target from it, casts it to an HTMLElement, and gets the innerHTML text of the button.

Then, it decides which action based on the text of the menu button.

This same technique can be used for dynamically generated menu items, where the menu name is not hardcoded, but is set by variable.