From db1d51f9a3ead41cbd3254390ae1a0c09e5ae8d6 Mon Sep 17 00:00:00 2001 From: Kristiyan Kostadinov Date: Wed, 29 Aug 2018 19:15:18 +0200 Subject: [PATCH] fix(badge): apply view encapsulation attributes on badge element (#12870) Since we create the badge content element dynamically, the view encapsulation attributes won't be applied. These changes use the renderer to create the element, which will respect view encapsulation. --- src/lib/badge/badge.spec.ts | 19 ++++++++++++++++++- src/lib/badge/badge.ts | 19 ++++++++++++++++--- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/src/lib/badge/badge.spec.ts b/src/lib/badge/badge.spec.ts index 88cf899b4af..ff1ea263ab7 100644 --- a/src/lib/badge/badge.spec.ts +++ b/src/lib/badge/badge.spec.ts @@ -1,5 +1,5 @@ import {ComponentFixture, TestBed, fakeAsync} from '@angular/core/testing'; -import {Component, DebugElement} from '@angular/core'; +import {Component, DebugElement, ViewEncapsulation} from '@angular/core'; import {By} from '@angular/platform-browser'; import {MatBadge, MatBadgeModule} from './index'; import {ThemePalette} from '@angular/material/core'; @@ -140,10 +140,27 @@ describe('MatBadge', () => { expect(classList.contains('mat-badge-hidden')).toBe(false); }); + it('should apply view encapsulation on create badge content', () => { + const badge = badgeNativeElement.querySelector('.mat-badge-content')!; + let encapsulationAttr: Attr | undefined; + + for (let i = 0; i < badge.attributes.length; i++) { + if (badge.attributes[i].name.startsWith('_ngcontent-')) { + encapsulationAttr = badge.attributes[i]; + break; + } + } + + expect(encapsulationAttr).toBeTruthy(); + }); + }); /** Test component that contains a MatBadge. */ @Component({ + // Explicitly set the view encapsulation since we have a test that checks for it. + encapsulation: ViewEncapsulation.Emulated, + styles: ['span { color: hotpink; }'], template: ` , - private _ariaDescriber: AriaDescriber) {} + private _ariaDescriber: AriaDescriber, + /** @breaking-change 8.0.0 Make _renderer a required param and remove _document. */ + private _renderer?: Renderer2) {} /** Whether the badge is above the host or not */ isAbove(): boolean { @@ -132,7 +143,9 @@ export class MatBadge implements OnDestroy { /** Creates the badge element */ private _createBadgeElement(): HTMLElement { - const badgeElement = this._document.createElement('span'); + // @breaking-change 8.0.0 Remove null check for _renderer + const rootNode = this._renderer || this._document; + const badgeElement = rootNode.createElement('span'); const activeClass = 'mat-badge-active'; badgeElement.setAttribute('id', `mat-badge-content-${this._id}`);