mirror of
https://github.com/angular/angular.git
synced 2026-09-14 13:54:52 +08:00
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:
@@ -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 {
|
||||
}
|
||||
|
||||
@@ -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 */
|
||||
|
||||
Reference in New Issue
Block a user