From bdc681108b9acd02fa1fb0729b8b11315724cdf0 Mon Sep 17 00:00:00 2001 From: crisbeto Date: Thu, 23 May 2019 19:08:26 +0200 Subject: [PATCH] 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. --- src/material/badge/badge.spec.ts | 17 ++++++++++++++++- src/material/badge/badge.ts | 8 ++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) 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 */