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.
This commit is contained in:
crisbeto
2019-05-23 19:08:26 +02:00
committed by mmalerba
parent 254fb49b1f
commit bdc681108b
2 changed files with 24 additions and 1 deletions
+16 -1
View File
@@ -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: `
<ng-template matBadge="1">Notifications</ng-template>
`
})
class BadgeOnTemplate {
}
+8
View File
@@ -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 */