diff --git a/src/lib/badge/badge.spec.ts b/src/lib/badge/badge.spec.ts index e1f7e70f20b..88cf899b4af 100644 --- a/src/lib/badge/badge.spec.ts +++ b/src/lib/badge/badge.spec.ts @@ -114,6 +114,32 @@ describe('MatBadge', () => { expect(badgeContent.getAttribute('aria-describedby')).toBeFalsy(); }); + it('should toggle visibility based on whether the badge has content', () => { + const classList = badgeNativeElement.classList; + + expect(classList.contains('mat-badge-hidden')).toBe(false); + + testComponent.badgeContent = ''; + fixture.detectChanges(); + + expect(classList.contains('mat-badge-hidden')).toBe(true); + + testComponent.badgeContent = 'hello'; + fixture.detectChanges(); + + expect(classList.contains('mat-badge-hidden')).toBe(false); + + testComponent.badgeContent = ' '; + fixture.detectChanges(); + + expect(classList.contains('mat-badge-hidden')).toBe(true); + + testComponent.badgeContent = 0; + fixture.detectChanges(); + + expect(classList.contains('mat-badge-hidden')).toBe(false); + }); + }); /** Test component that contains a MatBadge. */ @@ -132,7 +158,7 @@ describe('MatBadge', () => { }) class BadgeTestApp { badgeColor: ThemePalette; - badgeContent = '1'; + badgeContent: string | number = '1'; badgeDirection = 'above after'; badgeHidden = false; badgeSize = 'medium'; diff --git a/src/lib/badge/badge.ts b/src/lib/badge/badge.ts index 25f42d5c4df..0b72ee08353 100644 --- a/src/lib/badge/badge.ts +++ b/src/lib/badge/badge.ts @@ -31,10 +31,12 @@ export type MatBadgeSize = 'small' | 'medium' | 'large'; '[class.mat-badge-small]': 'size === "small"', '[class.mat-badge-medium]': 'size === "medium"', '[class.mat-badge-large]': 'size === "large"', - '[class.mat-badge-hidden]': 'hidden', + '[class.mat-badge-hidden]': 'hidden || !_hasContent', }, }) export class MatBadge implements OnDestroy { + /** Whether the badge has any content. */ + _hasContent = false; /** The color of the badge. Can be `primary`, `accent`, or `warn`. */ @Input('matBadgeColor') @@ -62,8 +64,9 @@ export class MatBadge implements OnDestroy { /** The content for the badge */ @Input('matBadge') get content(): string { return this._content; } - set content(val: string) { - this._content = val; + set content(value: string) { + this._content = value; + this._hasContent = value != null && `${value}`.trim().length > 0; this._updateTextContent(); } private _content: string;