I have and Angular app, and as part of it I show query result in a div (has ID of JSONContainer).
I wanted to highlight the specific query inside the result, so I used a pipe that searchs the results, and replaces the FIELD:VALUE in the text with:
<span class="highlightSpan">FIELD:VALUE</span>.
I added the following css to the component:
div#JSONContainer span.highlightSpan{
background-color: rgba(28, 243, 28, 0.5) !important;
color:red !important;
padding: 1px;
margin:1px;
}
I tried adding the same style under .highlightSpan as well, with the same results.
I insert this span and the rest of the text via innerHTML in the containing component, using the 'data' variable, that stores the entire JSON, and 'query' variable that stores the query:
<div class="col-xs-12" id="JSONContainer"
[innerHTML]="data | textHighlight:query">
</div>
(I'm not using string interpolation because the data var is json shaped which I styled using html code,like html br tag, and string interpolation shows only text).
When I point my mouse to the relevent span in google dev tools, I see that the span with the class was created:
But the css style is not applyed, and its not even showing in google dev tools:
EDIT: I know it dosen't show (I erased it from the img), but the span is located in the div#JSONContainr, as described.
EDIT 2: Here is the relevant tree:
Why is this happening?
How to make the css style apply?
Thanks!
This happens because you are adding the span
element dynamically and it is not part of your component, therefore the span
element is not decorated with component style isolation. When you explore your components rendered html then you see that each element has attribute like _ngcontent-c2
but your span doesn't, so it is not part of that component styling.
You can change your css to:
::ng-deep div#JSONContainer span.highlightSpan
to style descendants of your component (other components or elements added dynamically). Or you can add the styling to your global style so it is not part of that component isolation.
I have created stackblitz demo to simulate your situation.
You can read more about angular view encapsulation.