0

I have this element with badge and I would like to add onClick on the badge, but in this case the onClick reacts on the text click, how can I do it ONLY for the badge?

<div matBadge="i" matBadgeOverlap="false" (click)="onClick()">Text with badge </div>
Ostap Filipenko
  • 235
  • 5
  • 21

3 Answers3

2

This is an issue that was also raised once to the material team back in 2018 on GitHub.

Answer:

Badges are intended to be for displaying information only and aren't meant to be interactive. Introducing interactions on them would lead to accessibility problems, so this isn't something we would support.

MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43
1

Badge elements have the style 'pointer-events: none', which is why you don't get the click events. You can use Javascript to query the inner implementation element and change this style.

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.

Only drawback with this approach is that it's susceptible to break if the matBadge implementation changes as that can happen during major framework overhauls.

Hari Mahadevan
  • 920
  • 7
  • 14
0

You could suround the badge by a span and add the click event listener to it:

<div matBadge="i" matBadgeOverlap="false">Text with <span (click)="onClick()">badge</span></div>
Veso Alex
  • 76
  • 5