diff --git a/src/material/badge/badge.spec.ts b/src/material/badge/badge.spec.ts index 12ac5f24434a..6283f7077c5b 100644 --- a/src/material/badge/badge.spec.ts +++ b/src/material/badge/badge.spec.ts @@ -14,7 +14,7 @@ describe('MatBadge', () => { TestBed .configureTestingModule({ imports: [MatBadgeModule], - declarations: [BadgeTestApp, PreExistingBadge, NestedBadge], + declarations: [BadgeTestApp, PreExistingBadge, NestedBadge, BadgeOnTemplate], }) .compileComponents(); @@ -205,6 +205,12 @@ describe('MatBadge', () => { expect(fixture.componentInstance.badgeInstance.getBadgeElement()).toBe(badgeElement); }); + it('should throw if badge is not attached to an element node', () => { + expect(() => { + TestBed.createComponent(BadgeOnTemplate); + }).toThrowError(/matBadge must be attached to an element node/); + }); + }); /** Test component that contains a MatBadge. */ @@ -260,3 +266,12 @@ class PreExistingBadge { }) class NestedBadge { } + + +@Component({ + template: ` + Notifications + ` +}) +class BadgeOnTemplate { +} diff --git a/src/material/badge/badge.ts b/src/material/badge/badge.ts index a8019a03e0fd..5fc3222d9e5c 100644 --- a/src/material/badge/badge.ts +++ b/src/material/badge/badge.ts @@ -19,6 +19,7 @@ import { Optional, Renderer2, SimpleChanges, + isDevMode, } from '@angular/core'; import {CanDisable, CanDisableCtor, mixinDisabled, ThemePalette} from '@angular/material/core'; import {ANIMATION_MODULE_TYPE} from '@angular/platform-browser/animations'; @@ -124,6 +125,13 @@ export class MatBadge extends _MatBadgeMixinBase implements OnDestroy, OnChanges private _renderer: Renderer2, @Optional() @Inject(ANIMATION_MODULE_TYPE) private _animationMode?: string) { super(); + + if (isDevMode()) { + const nativeElement = _elementRef.nativeElement; + if (nativeElement.nodeType !== nativeElement.ELEMENT_NODE) { + throw Error('matBadge must be attached to an element node.'); + } + } } /** Whether the badge is above the host or not */