Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material - Empty Badge

I'm currently adding badges to the buttons of the menu of my application, which already works fine. I want to display the number of notifications the user still has to look at like this:

<span matBadge="4" matBadgeColor="warn">Look at these notifications!</span>

On a mobile phone though, the menu is hidden behind a burger icon. I don't want the user to show how many notifications he has on top of this icon. I only want him to know that he has some, and when he opens the menu, he will see a badge with the number of notifications on the various buttons.

My problem is that an empty badge is always hidden. I can't seem to show it like this:

<span matBadge="" matBadgeColor="warn">Look at these notifications!</span>

Is it not possible at all to show an empty badge? Am I missing something, or is this behaviour by design?

like image 434
Alexander Moser Avatar asked Oct 16 '18 14:10

Alexander Moser


4 Answers

Use [matBadgeHidden] = "true" for dynamically control visibility of matBadge, e.g.:

<span [matBadgeHidden] = "commentCount == 0"  [matBadge]="commentCount" matBadgeColor="warn" matBadgeOverlap="false">Comments</span>
like image 50
Aarji George Avatar answered Oct 25 '22 05:10

Aarji George


You will have to add a class for yourself to hide the text. The mat-badge has no functionality to hide the content. White space or &nbsp; will not work:

.mat-badge.hide-text .mat-badge-content {
  color: transparent;
}

<span matBadge="0" matBadgeColor="warn" class="hide-text">Look at these notifications!</span>

Update:

If you really don't want to use a class, you can use the &#8288;. This is a so called WORD JOINER. Mileage may vary with Angular version :), but this will print an empty badge

<span matBadge="&#8288;" matBadgeColor="warn">Look at these notifications!</span>
like image 44
Poul Kruijt Avatar answered Oct 25 '22 06:10

Poul Kruijt


In looking at the source for the badge component, it looks like this is by design due to lines:

'[class.mat-badge-hidden]': 'hidden || !_hasContent',
...
this._hasContent = value != null && `${value}`.trim().length > 0;

It does look like you can use matBadge="&#8203;" to have an empty badge show to work around this.

like image 36
p4r1 Avatar answered Oct 25 '22 06:10

p4r1


You can add below css to display empty badge.

.mat-badge-hidden .mat-badge-content:empty {
  display: inline-block;
}

Have a look on below example.

https://stackblitz.com/edit/angular-mat-badge-with-pipe

like image 42
Lokesh Daiya Avatar answered Oct 25 '22 06:10

Lokesh Daiya