Skip to content

Commit

Permalink
fix(common): handle CSS custom properties in NgStyle (#46451)
Browse files Browse the repository at this point in the history
Fixes that `NgStyle` wasn't applying CSS custom properties.

PR Close #46451
  • Loading branch information
crisbeto authored and dylhunn committed Jun 24, 2022
1 parent c66b5c0 commit 42aed6b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
9 changes: 5 additions & 4 deletions packages/common/src/directives/ng_style.ts
Expand Up @@ -5,7 +5,7 @@
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, DoCheck, ElementRef, Input, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer2} from '@angular/core';
import {Directive, DoCheck, ElementRef, Input, KeyValueChanges, KeyValueDiffer, KeyValueDiffers, Renderer2, RendererStyleFlags2} from '@angular/core';


/**
Expand Down Expand Up @@ -71,12 +71,13 @@ export class NgStyle implements DoCheck {

private _setStyle(nameAndUnit: string, value: string|number|null|undefined): void {
const [name, unit] = nameAndUnit.split('.');
value = value != null && unit ? `${value}${unit}` : value;
const flags = name.indexOf('-') === -1 ? undefined : RendererStyleFlags2.DashCase as number;

if (value != null) {
this._renderer.setStyle(this._ngEl.nativeElement, name, value as string);
this._renderer.setStyle(
this._ngEl.nativeElement, name, unit ? `${value}${unit}` : value, flags);
} else {
this._renderer.removeStyle(this._ngEl.nativeElement, name);
this._renderer.removeStyle(this._ngEl.nativeElement, name, flags);
}
}

Expand Down
18 changes: 18 additions & 0 deletions packages/common/test/directives/ng_style_spec.ts
Expand Up @@ -14,6 +14,10 @@ import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
describe('NgStyle', () => {
let fixture: ComponentFixture<TestComponent>;

const supportsCssVariables = typeof getComputedStyle !== 'undefined' &&
typeof CSS !== 'undefined' && typeof CSS.supports !== 'undefined' &&
CSS.supports('color', 'var(--fake-var)');

function getComponent(): TestComponent {
return fixture.componentInstance;
}
Expand Down Expand Up @@ -192,6 +196,20 @@ import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
fixture.detectChanges();
expectNativeEl(fixture).toHaveCssStyle({'width': '400px'});
});

it('should handle CSS variables', () => {
if (!supportsCssVariables) {
return;
}

const template = `<div style="width: var(--width)" [ngStyle]="{'--width': expr}"></div>`;
fixture = createTestComponent(template);
fixture.componentInstance.expr = '100px';
fixture.detectChanges();

const target: HTMLElement = fixture.nativeElement.querySelector('div');
expect(getComputedStyle(target).getPropertyValue('width')).toEqual('100px');
});
});
}

Expand Down

0 comments on commit 42aed6b

Please sign in to comment.