Skip to content

Commit

Permalink
fix(ngStyle): should work with preexisting styles (#939)
Browse files Browse the repository at this point in the history
  • Loading branch information
CaerusKaru authored and ThomasBurleson committed Dec 18, 2018
1 parent 7759b6c commit 4be5cef
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
13 changes: 13 additions & 0 deletions src/lib/extended/style/style.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,18 @@ describe('style directive', () => {
matchMedia.activate('xs');
expectNativeEl(fixture, {fontSize: 19}).toHaveStyle({'font-size': '19px'}, styler);
});

it('should work with just ngStyle and preexisting styles', () => {
createTestComponent(`
<div style="background-color: red; height: 100px; width: 100px;" [ngStyle]="divStyle">
First div
</div>
`);
expectNativeEl(fixture).toHaveStyle({'background-color': 'red'}, styler);
expectNativeEl(fixture).toHaveStyle({'height': '100px'}, styler);
expectNativeEl(fixture).toHaveStyle({'width': '100px'}, styler);
expectNativeEl(fixture).toHaveStyle({'border': '2px solid green'}, styler);
});
});

// *****************************************************************
Expand All @@ -156,6 +168,7 @@ describe('style directive', () => {
})
class TestStyleComponent {
fontSize: number = 0;
divStyle = {'border': '2px solid green'};
}


Expand Down
8 changes: 4 additions & 4 deletions src/lib/extended/style/style.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
export class StyleDirective extends BaseDirective2 implements DoCheck {

protected DIRECTIVE_KEY = 'ngStyle';
protected fallbackStyles: NgStyleMap = {};

constructor(protected elementRef: ElementRef,
protected styler: StyleUtils,
Expand All @@ -50,14 +51,13 @@ export class StyleDirective extends BaseDirective2 implements DoCheck {
this.ngStyleInstance = new NgStyle(this.keyValueDiffers, this.elementRef, this.renderer);
}
this.init();
this.setValue(this.nativeElement.getAttribute('style') || '', '');
const styles = this.nativeElement.getAttribute('style') || '';
this.fallbackStyles = this.buildStyleMap(styles);
}

protected updateWithValue(value: any) {
const styles = this.buildStyleMap(value);
const defaultStyles = this.marshal.getValue(this.nativeElement, this.DIRECTIVE_KEY, '');
const fallback = this.buildStyleMap(defaultStyles);
this.ngStyleInstance.ngStyle = {...fallback, ...styles};
this.ngStyleInstance.ngStyle = {...this.fallbackStyles, ...styles};
this.ngStyleInstance.ngDoCheck();
}

Expand Down

0 comments on commit 4be5cef

Please sign in to comment.