Angular Material - 空徽章

Angular Material - Empty Badge

我目前正在为我的应用程序菜单按钮添加徽章,这已经可以正常工作了。我想像这样显示用户仍然需要查看的通知数量:

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

不过在移动设备上 phone,菜单隐藏在汉堡图标后面。我不希望用户在此图标之上显示他有多少通知。我只想让他知道他有一些,当他打开菜单时,他会在各个按钮上看到一个带有通知数量的徽章。

我的问题是总是隐藏空徽章。我好像不能这样显示:

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

是不是完全不能显示一个空徽章?我是不是遗漏了什么,或者这是设计使然的行为?

您必须为自己添加一个 class 来隐藏文本。 mat-badge 没有隐藏内容的功能。白色 space 或 &nbsp; 将不起作用:

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

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

更新:

如果实在不想用class,可以用&#8288;。这就是所谓的WORD JOINER。里程数可能因 Angular 版本而异 :),但这将打印一个空徽章

<span matBadge="&#8288;" matBadgeColor="warn">Look at these notifications!</span>

在查看 source for the badge component 时,看起来这是设计使然:

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

看起来您确实可以使用 matBadge="&#8203;" 显示空白徽章来解决此问题。

您可以在下面添加 css 以显示空徽章。

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

看看下面的例子。

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

使用 [matBadgeHidden] = "true" 动态控制 matBadge 的可见性, 例如:

<span [matBadgeHidden] = "commentCount == 0"  [matBadge]="commentCount" matBadgeColor="warn" matBadgeOverlap="false">Comments</span>