Skip to content
This repository was archived by the owner on Jan 6, 2025. It is now read-only.

Commit 4be5cef

Browse files
CaerusKaruThomasBurleson
authored andcommitted
fix(ngStyle): should work with preexisting styles (#939)
1 parent 7759b6c commit 4be5cef

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

src/lib/extended/style/style.spec.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,18 @@ describe('style directive', () => {
144144
matchMedia.activate('xs');
145145
expectNativeEl(fixture, {fontSize: 19}).toHaveStyle({'font-size': '19px'}, styler);
146146
});
147+
148+
it('should work with just ngStyle and preexisting styles', () => {
149+
createTestComponent(`
150+
<div style="background-color: red; height: 100px; width: 100px;" [ngStyle]="divStyle">
151+
First div
152+
</div>
153+
`);
154+
expectNativeEl(fixture).toHaveStyle({'background-color': 'red'}, styler);
155+
expectNativeEl(fixture).toHaveStyle({'height': '100px'}, styler);
156+
expectNativeEl(fixture).toHaveStyle({'width': '100px'}, styler);
157+
expectNativeEl(fixture).toHaveStyle({'border': '2px solid green'}, styler);
158+
});
147159
});
148160

149161
// *****************************************************************
@@ -156,6 +168,7 @@ describe('style directive', () => {
156168
})
157169
class TestStyleComponent {
158170
fontSize: number = 0;
171+
divStyle = {'border': '2px solid green'};
159172
}
160173

161174

src/lib/extended/style/style.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ import {
3535
export class StyleDirective extends BaseDirective2 implements DoCheck {
3636

3737
protected DIRECTIVE_KEY = 'ngStyle';
38+
protected fallbackStyles: NgStyleMap = {};
3839

3940
constructor(protected elementRef: ElementRef,
4041
protected styler: StyleUtils,
@@ -50,14 +51,13 @@ export class StyleDirective extends BaseDirective2 implements DoCheck {
5051
this.ngStyleInstance = new NgStyle(this.keyValueDiffers, this.elementRef, this.renderer);
5152
}
5253
this.init();
53-
this.setValue(this.nativeElement.getAttribute('style') || '', '');
54+
const styles = this.nativeElement.getAttribute('style') || '';
55+
this.fallbackStyles = this.buildStyleMap(styles);
5456
}
5557

5658
protected updateWithValue(value: any) {
5759
const styles = this.buildStyleMap(value);
58-
const defaultStyles = this.marshal.getValue(this.nativeElement, this.DIRECTIVE_KEY, '');
59-
const fallback = this.buildStyleMap(defaultStyles);
60-
this.ngStyleInstance.ngStyle = {...fallback, ...styles};
60+
this.ngStyleInstance.ngStyle = {...this.fallbackStyles, ...styles};
6161
this.ngStyleInstance.ngDoCheck();
6262
}
6363

0 commit comments

Comments
 (0)