Skip to content

fix(badge): hide badges with no content #12239

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 18, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion src/lib/badge/badge.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand All @@ -132,7 +158,7 @@ describe('MatBadge', () => {
})
class BadgeTestApp {
badgeColor: ThemePalette;
badgeContent = '1';
badgeContent: string | number = '1';
badgeDirection = 'above after';
badgeHidden = false;
badgeSize = 'medium';
Expand Down
9 changes: 6 additions & 3 deletions src/lib/badge/badge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down Expand Up @@ -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;
Expand Down