Skip to content

Commit bdc6811

Browse files
crisbetommalerba
authored andcommitted
fix(badge): throw proper error when set on a non-element node
Currently if a `matBadge` is set on a non-element node, we eventually hit an error that can look cryptic. This changes add a proper error so it's easier to debug.
1 parent 254fb49 commit bdc6811

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/material/badge/badge.spec.ts

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ describe('MatBadge', () => {
1414
TestBed
1515
.configureTestingModule({
1616
imports: [MatBadgeModule],
17-
declarations: [BadgeTestApp, PreExistingBadge, NestedBadge],
17+
declarations: [BadgeTestApp, PreExistingBadge, NestedBadge, BadgeOnTemplate],
1818
})
1919
.compileComponents();
2020

@@ -205,6 +205,12 @@ describe('MatBadge', () => {
205205
expect(fixture.componentInstance.badgeInstance.getBadgeElement()).toBe(badgeElement);
206206
});
207207

208+
it('should throw if badge is not attached to an element node', () => {
209+
expect(() => {
210+
TestBed.createComponent(BadgeOnTemplate);
211+
}).toThrowError(/matBadge must be attached to an element node/);
212+
});
213+
208214
});
209215

210216
/** Test component that contains a MatBadge. */
@@ -260,3 +266,12 @@ class PreExistingBadge {
260266
})
261267
class NestedBadge {
262268
}
269+
270+
271+
@Component({
272+
template: `
273+
<ng-template matBadge="1">Notifications</ng-template>
274+
`
275+
})
276+
class BadgeOnTemplate {
277+
}

src/material/badge/badge.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
Optional,
2020
Renderer2,
2121
SimpleChanges,
22+
isDevMode,
2223
} from '@angular/core';
2324
import {CanDisable, CanDisableCtor, mixinDisabled, ThemePalette} from '@angular/material/core';
2425
import {ANIMATION_MODULE_TYPE} from '@angular/platform-browser/animations';
@@ -124,6 +125,13 @@ export class MatBadge extends _MatBadgeMixinBase implements OnDestroy, OnChanges
124125
private _renderer: Renderer2,
125126
@Optional() @Inject(ANIMATION_MODULE_TYPE) private _animationMode?: string) {
126127
super();
128+
129+
if (isDevMode()) {
130+
const nativeElement = _elementRef.nativeElement;
131+
if (nativeElement.nodeType !== nativeElement.ELEMENT_NODE) {
132+
throw Error('matBadge must be attached to an element node.');
133+
}
134+
}
127135
}
128136

129137
/** Whether the badge is above the host or not */

0 commit comments

Comments
 (0)