Skip to content

Commit

Permalink
fix(core): preserve static class/styles on root component
Browse files Browse the repository at this point in the history
Fix to preserve statically applied classes and styles on root component while using host binding.

Fixes angular#51460
  • Loading branch information
chintankavathia committed Sep 4, 2024
1 parent 8da9fb4 commit c76ae06
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
16 changes: 14 additions & 2 deletions packages/core/src/render3/node_manipulation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1280,10 +1280,22 @@ export function setupStaticAttributes(renderer: Renderer, element: RElement, tNo
}

if (classes !== null) {
writeDirectClass(renderer, element, classes);
const elementClasses = element.className.split
? (element.className
.split(' ')
.filter((item) => !classes.includes(item))
.join(' ') ?? '')
: '';
writeDirectClass(renderer, element, `${classes} ${elementClasses}`.trim());
}

if (styles !== null) {
writeDirectStyle(renderer, element, styles);
const elementStyles =
element
.getAttribute('style')
?.split(';')
.filter((item) => !styles.includes(item))
.join(';') ?? '';
writeDirectStyle(renderer, element, `${styles} ${elementStyles}`.trim());
}
}
26 changes: 26 additions & 0 deletions packages/core/test/acceptance/bootstrap_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import {
ViewEncapsulation,
ɵNoopNgZone,
ɵZONELESS_ENABLED,
ElementRef,
} from '@angular/core';
import {bootstrapApplication, BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
Expand Down Expand Up @@ -82,6 +83,31 @@ describe('bootstrap', () => {
}),
);

it(
'should preserve static class and styles on root component',
withBody('<test-cmp class="foo" style="height: 100%"></test-cmp>', async () => {
@Component({
selector: 'test-cmp',
standalone: true,
template: '(test)',
host: {
class: 'baar',
style: 'width: 100%;',
},
})
class TestCmp {
constructor(public element: ElementRef) {}
}
const appRef = await bootstrapApplication(TestCmp);
expect(appRef.components[0].instance.element.nativeElement.className).toBe('baar foo');
expect(appRef.components[0].instance.element.nativeElement.getAttribute('style')).toBe(
'width: 100%; height: 100%',
);

appRef.destroy();
}),
);

describe('options', () => {
function createComponentAndModule(
options: {
Expand Down

0 comments on commit c76ae06

Please sign in to comment.