Skip to content

Commit

Permalink
fix(common): ngStyle should filter out undefined values
Browse files Browse the repository at this point in the history
Prior to ivy, undefined values passed in an object to the
ngStyle directive were ignored. Restore this behavior by
filtering out keys that point to undefined values.

closes #34310
  • Loading branch information
mnahkies committed Dec 16, 2019
1 parent f79110c commit a9341fa
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
16 changes: 15 additions & 1 deletion packages/common/src/directives/ng_style_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,9 @@ export class NgStyleR3Impl implements NgStyleImpl {

getValue() { return this._value; }

setNgStyle(value: {[key: string]: any}|null) { this._differ.setValue(value); }
setNgStyle(value: {[key: string]: any}|null) {
this._differ.setValue(value ? filterOutUndefinedValues(value) : value);
}

applyChanges() {
if (this._differ.hasValueChanged()) {
Expand All @@ -98,6 +100,18 @@ export class NgStyleR3Impl implements NgStyleImpl {
}
}

function filterOutUndefinedValues(obj: Record<string, any>) {
const result: Record<string, string|null> = {};

for (let key in obj) {
if (obj[key] !== undefined) {
result[key] = obj[key];
}
}

return result;
}

// the implementation for both NgClassR2Impl and NgClassR3Impl are
// not ivy_switch'd away, instead they are only hooked up into the
// DI via NgStyle's directive's provider property.
Expand Down
23 changes: 23 additions & 0 deletions packages/common/test/directives/ng_style_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,29 @@ import {ComponentFixture, TestBed, async} from '@angular/core/testing';
expectNativeEl(fixture).not.toHaveCssStyle('max-width');
expectNativeEl(fixture).toHaveCssStyle({'font-size': '12px'});
}));

it('should skip keys that are set to undefined values', async(() => {
const template = `<div [ngStyle]="expr"></div>`;

fixture = createTestComponent(template);

getComponent().expr = {
'border-top-color': undefined,
'border-top-style': undefined,
'border-color': 'red',
'border-style': 'solid',
'border-width': '1rem',
};

fixture.detectChanges();

expectNativeEl(fixture).toHaveCssStyle({
'border-color': 'red',
'border-style': 'solid',
'border-width': '1rem',
});
}));

});
}

Expand Down

0 comments on commit a9341fa

Please sign in to comment.