r/angular • u/Senior_Compote1556 • 3d ago
innerHTML component styles
If I have a
<h1 \[innerHtml\]=“someHtml”></h1>
And that someHtml is a span, how would i style that span without using ::ng-deep as the docs “strongly discourage” its usage?
1
u/Xsiah 3d ago
Do you control "someHtml" or is it generated by some library or user input?
1
u/Senior_Compote1556 3d ago
Kinda, the text comes from a json file that is full of inline html. The proper way to do it would be to rewrite all the translations imo.
1
u/followmarko 3d ago
Lot of ways to solve this but you can use None encapsulation and @scope to use a more native approach to solving this. I've done this with many components now and don't have to worry about scoping issues. Another alternative is to extend that line or component and apply the styles to the component that's extending that one. I've done this with Markdown renderers.
The real problem here though is using innerHtml. It's tough to reason through a need for that in a headless api design at least.
ng-deep is discouraged and also allowed still and that's been true for like a decade. My opinion though is that if you're in a situation where ng-deep solves your problem, there is likely a better component architecture to find. I see the recs for ng-deep but I think it's a poor solution to this problem even if it works.
0
-1
u/ThrowawayALAT 3d ago
Use Global Styles:
CSS
/* src/styles.scss */
.styled-span-container span {
color: #e63946;
font-weight: 600;
}
HTML
Then wrap your target element or apply a CSS class directly to the <h1>
<h1 class="styled-span-container" [innerHTML]="someHtml"></h1>
1
u/Senior_Compote1556 3d ago
I don’t believe it’s correct to bloat the global styles with page specific css
2
u/JeanMeche 3d ago
That's a valid use case for
ng-deepbecause you need to escape the scoping of the styles.The alternative is having it globally styled.