Skip to content

Commit 712f47a

Browse files
fix(host-binding): allow to bind the style property with an object to set multiple CSS properties (including variables) at once (#617)
* test(host-binding): add new test to verify that the hostBinding function accepts an object for style binding * fix(host-binding): allow to pass an object for style binding * refactor(host-binding): do not throw an error if the "property" and/or the value is undefined or null
1 parent e5a98cb commit 712f47a

File tree

2 files changed

+36
-8
lines changed

2 files changed

+36
-8
lines changed

libs/ngxtension/host-binding/src/host-binding.spec.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,14 @@ class TestHost {
5252
// style binding with a style unit extension
5353
width = hostBinding('style.width.px', signal(500));
5454

55+
style = hostBinding(
56+
'style',
57+
signal({
58+
position: 'fixed',
59+
top: '10px',
60+
} satisfies Partial<CSSStyleDeclaration>),
61+
);
62+
5563
// attribute binding
5664
required = hostBinding(
5765
'attr.aria-required',
@@ -152,6 +160,13 @@ describe(hostBinding.name, () => {
152160

153161
expect(fixture.nativeElement.style.width).toEqual('500px');
154162
});
163+
164+
it('should bind both position to "fixed" and top to "10px"', () => {
165+
const { fixture } = setup();
166+
167+
expect(fixture.nativeElement.style.position).toEqual('fixed');
168+
expect(fixture.nativeElement.style.top).toEqual('10px');
169+
});
155170
});
156171

157172
describe('attribute binding', () => {

libs/ngxtension/host-binding/src/host-binding.ts

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,27 @@ export function hostBinding<T, S extends Signal<T> | WritableSignal<T>>(
5151

5252
switch (binding) {
5353
case 'style':
54-
renderer.setStyle(
55-
element,
56-
property,
57-
`${value}${unit ?? ''}`,
58-
property.startsWith('--')
59-
? RendererStyleFlags2.DashCase
60-
: undefined,
61-
);
54+
if (property) {
55+
renderer.setStyle(
56+
element,
57+
property,
58+
`${value}${unit ?? ''}`,
59+
property.startsWith('--')
60+
? RendererStyleFlags2.DashCase
61+
: undefined,
62+
);
63+
} else if (typeof value === 'object' && value !== null) {
64+
for (const [style, val] of Object.entries(value)) {
65+
renderer.setStyle(
66+
element,
67+
style,
68+
val,
69+
style.startsWith('--')
70+
? RendererStyleFlags2.DashCase
71+
: undefined,
72+
);
73+
}
74+
}
6275
break;
6376
case 'attr':
6477
if (value == null) {

0 commit comments

Comments
 (0)