24

Using angular/material 6.2.1, I am trying to add a badge to a button, which works fine. However, instead of showing plain text that I can set by using the matBadge directive, I would like the badge to show a material icon instead.

Does anyone know what I have to do to achieve this? I suppose I could use jQuery but I am wondering whether there might be a smoother/easier way to do so.

Kim Kern
  • 54,283
  • 17
  • 197
  • 195
van_Skyr
  • 613
  • 2
  • 5
  • 8

3 Answers3

27

I solved this by simply setting f.e. matBadge="person" on the button.

And then in your css file:

.mat-badge-content {
    font-family: 'Material Icons';
}
Kris
  • 824
  • 2
  • 12
  • 28
13

There is nothing exposed in their API to achieve it at the moment. You have to manipulate the DOM by yourself:

$0.innerHTML = '<i class="material-icons">check</icon>'

You can write a simple directive to do it in a elegant and reusable way:

@Directive({
  selector: '[matBadgeIcon]'
})
export class MatBadgeIconDirective {

  @Input() matBadgeIcon: string;

  constructor(private el: ElementRef) {}

  ngOnInit() {
    const badge = this.el.nativeElement.querySelector('.mat-badge-content');
    badge.style.display = 'flex';
    badge.style.alignItems = 'center';
    badge.style.justifyContent = 'center';
    badge.innerHTML = `<i class="material-icons" style="font-size: 20px">${this.matBadgeIcon}</i>`;
  }
}

Usage: <div matBadge matBadgeIcon="check">...</div>

Otherwise there is a lot of plain text symbols that you can use like ★✎♥ ,...

Alexandre Annic
  • 9,942
  • 5
  • 36
  • 50
8

This answer is for those who want to use long string inside the badge:

Changing only the CSS:

.custom-badge {

  .mat-badge-content {

    width: fit-content;
    text-align: center;
    border-radius: 7px;
    left: 13px;
  }
}

in template:

<mat-icon 
class="custom-badge"
matBadge="1,2,4"
matBadgePosition="after" 
matBadgeColor="accent"
[matBadgeHidden]="myExpresion" 
>
 report_problem
</mat-icon>
noririco
  • 765
  • 6
  • 15