简体   繁体   中英

span doesn't apply css style when entered via innerHTML

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!

In your PIPE you have to import

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

Add to constructor

  constructor(private sanitizer: DomSanitizer) {
  }

In transform function return

this.sanitizer.bypassSecurityTrustHtml('YOUR HTML');

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM