Skip to content

Commit

Permalink
fix(badge): throw proper error when set on a non-element node
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
crisbeto authored and mmalerba committed May 23, 2019
1 parent 254fb49 commit bdc6811
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
17 changes: 16 additions & 1 deletion src/material/badge/badge.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ describe('MatBadge', () => {
TestBed
.configureTestingModule({
imports: [MatBadgeModule],
declarations: [BadgeTestApp, PreExistingBadge, NestedBadge],
declarations: [BadgeTestApp, PreExistingBadge, NestedBadge, BadgeOnTemplate],
})
.compileComponents();

Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -260,3 +266,12 @@ class PreExistingBadge {
})
class NestedBadge {
}


@Component({
template: `
<ng-template matBadge="1">Notifications</ng-template>
`
})
class BadgeOnTemplate {
}
8 changes: 8 additions & 0 deletions src/material/badge/badge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 */
Expand Down

0 comments on commit bdc6811

Please sign in to comment.