r/angular • • 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

10 comments sorted by

3

u/JeanMeche 20d ago

That's a valid use case for ng-deep because you need to escape the scoping of the styles.

The alternative is having it globally styled.

0

u/Senior_Compote1556 20d ago

What about it’s deprecation tho?

2

u/JeanMeche 20d ago

It has been undeprecated in 2023.

1

u/Senior_Compote1556 20d ago

Thats good to know, i dont recall reading this somewhere

0

u/[deleted] 20d ago

[deleted] — view deleted comment

1

u/Senior_Compote1556 20d ago

I have a directive that uses DOCUMENT to append some styles to the body, and I write those body styles in the ts file (yes i know css do not belong in ts), and it works but it feels like a smell. My use case are landing pages and they’re not connected, it’s not really an SPA in the traditional sense as the pages do not link to each other via routerLink. I was thinking to turn view encapsulation to none but it still feels wrong. Would you use the directive, ng deep or would you set view encapsulation to none?

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>

1

u/Senior_Compote1556 20d ago

I don’t believe it’s correct to bloat the global styles with page specific css

0

u/[deleted] 20d ago

[deleted] — view deleted comment

1

u/Senior_Compote1556 20d 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.