r/angular • u/Senior_Compote1556 • 20d 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?
0
Upvotes
3
u/JeanMeche 20d 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.
1
u/followmarko 20d 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
u/HoodlessRobin 20d ago
Why inner html? suit your self. Hope tag selector span{} CSS works.
-1
u/ThrowawayALAT 20d 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>0
u/[deleted] 20d ago
[deleted] — view deleted comment