Enabling click on Material Badge component

• 4 min read

In Angular Material, badge elements are declared as a directive on the host element around which the badge is to be placed. Depending on the value of other related directives, the badge is placed before or after and above or below the element. But if you try to bind a click handler on the host element itself, you'll find that the click only works on the host and not on the badge element which is typically positioned outside the host element.

As it turns out, the badge implementation creates a child element to the host which is positioned accordingly with the content specified as value to the matBadge directive. This child element has the style pointer-events: none, which is why you don't get the click events. So to enable click events, all you have to do is to remove this style or change its value to inherit. You can use Javascript to do this.

So for the following HTML:

<div id="todo-actions" matBadge="!" matBadgeOverlap="false" matBadgeColor="warn">&nbsp;</div>

This code will do the trick:

    const todoBadge: HTMLElement = document.querySelector("#todo-actions .mat-badge-content");
    if (todoBadge) {
      todoBadge.style.pointerEvents = "inherit";
    }

Note that the .mat-badge-content is the inner element created by the matBadge directive. Using #todo-actions .mat-badge-content ensures that the CSS style is changed for the specific badge element.

Finally, if you're using Angular, put the JS code in your AfterViewInit handler so that the matBadge directive would have created its child element for the badge.

Only drawback with this approach is that it's not guaranteed to work if the matBadge implementation changes as that can happen during a major framework overhaul.