Styling is not being applied by span tags when inserted using innerHTML

I have a Angular application where I display query results in a div (identified by the ID JSONContainer).

To emphasize specific queries within the results, I implemented a pipe that searches for and replaces FIELD:VALUE with:

<span class="highlightSpan">FIELD:VALUE</span>.

I included the following CSS in the component:

div#JSONContainer span.highlightSpan{
    background-color: rgba(28, 243, 28, 0.5) !important;
    color:red !important;
    padding: 1px;
    margin:1px;
}

I also tried adding the same style under .highlightSpan, but encountered the same issue.

The span along with the rest of the text is inserted via innerHTML using the 'data' variable, which holds the entire JSON, and the 'query' variable holding the query:

    <div class="col-xs-12" id="JSONContainer"
        [innerHTML]="data | textHighlight:query">
    </div>

(I'm avoiding string interpolation as the data variable contains JSON formatted data styled with HTML code like
tags, and string interpolation displays just plain text.)

Upon inspecting the relevant span in Google Dev Tools, I confirmed that the span with the specified class was created:

https://i.sstatic.net/rWwkJ.jpg

However, the CSS styling is not being applied and doesn't even appear in Google Dev Tools:

https://i.sstatic.net/mAR6d.jpg

EDIT: Although it's not visible in the image, please note that the span is indeed located within the div#JSONContainr as mentioned.

EDIT 2: Here is the relevant tree structure:

https://i.sstatic.net/jvF7I.jpg

What could be causing this issue?

How can I ensure the CSS styles are successfully applied?

Thank you!

Answer №1

The issue arises when the span element is dynamically added and not included in your component, causing it to lack the component style isolation. Upon inspecting your components' rendered HTML, you will notice that each element has attributes like _ngcontent-c2, except for your span, indicating that it is not styled as part of that specific component.

To address this, you can modify your CSS to:

::ng-deep div#JSONContainer span.highlightSpan

This will enable you to style descendants of your component, including other components or dynamically-added elements. Alternatively, you can apply the styling globally so that it does not adhere to the component isolation.

I have prepared a demo on StackBlitz to mimic your scenario.

For further information on Angular view encapsulation, please refer to this resource.

Answer №2

When working with your PIPE, make sure to include the following import:

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

Ensure to add this to your constructor:

constructor(private sanitizer: DomSanitizer) {
}

Within your transform function, be sure to return:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular 4 is unable to attach to 'formGroup' as it is not recognized as a valid property of 'form'

As a beginner with Angular 4, I decided to explore model driven forms in Angular 4. However, I keep encountering this frustrating error. Template parse errors: Can't bind to 'formGroup' since it isn't a known property of 'form ...

Strategies for adjusting text size to fit within a resizable div container

I'm facing an issue with a resizable div that has text inside. When I resize the div, the last line of the text goes beyond the boundaries of the div. How can I ensure that all the text fits within the resizable div while maintaining the appropriate f ...

Tips on including starting information into an angularjs application from the displayed HTML

I'm currently working on a complex AngularJs application that requires User Login. Once the user is authenticated, a page will be displayed to them and additional data will be loaded later. There are two methods for achieving this: XHR Fetch af ...

Concentrate on utilizing the jquery tokeninput feature specifically for Chrome and Opera browsers

Encountering an issue with the tokeninput element in Chrome and Opera (Firefox is working fine). Even after selecting one or more elements, the tokeninput cannot lose focus. The cursor continues to blink even after selecting the last element, and clicking ...

Tips for adjusting the ion-select popup height in Ionic

I've been attempting to customize the max-height property of a div that organizes elements in a popup using the interfaceOptions attribute in Ionic, but so far I haven't been successful. Here's what I have tried: cu ...

Tips on using the Hover property in CSS for an element that includes both :after and :before properties

I've created a hexagon using CSS after and before properties, and now I'm attempting to add a glowing effect around the hexagon when hovering. It works perfectly for the center of the hexagon but not for the top and bottom points of the shape. ...

Tips for utilizing functions in an inline HTML translation pipe

My objective is to streamline the code by using the Angular translate pipe. Currently, I find myself using 8 curly brackets and repeating the word "translate" twice... there must be a more efficient approach. Here is my current code setup: <s ...

Discover the dimensions of the viewport using jQuery

I am currently attempting to use jQuery to determine the size of the viewport, but I am not achieving the desired results. Here is my CSS code: .site { max-width: 960px; } @media only screen and (min-width : 760px) and (max-width : 1040px) /* table ...

Debugging Slideshows Using JavaScript

I am currently working on creating a slideshow and I'm facing some challenges with the JavaScript functionality. Everything seems to be running smoothly except for one issue - when I click right once, it transitions correctly, but if I then click left ...

Unlawful CSS Selector

Wanting to utilize this particular CSS selector in conjunction with Selenium webdriver #coordinatonTable .odd:not(:has(.dataTables_empty)) Encountering an "An invalid or illegal string was specified" error. I've attempted the jquery selector test fr ...

RC7 is missing the necessary HTTP_PROVIDERS for the resolveAndCreate HTTP method in Angular2

During the time of RC4, I was able to create my own custom http instance using a function like this: export function createHTTP(url:string, headers?:Headers){ let injector = ReflectiveInjector.resolveAndCreate([ myHttp, {provide:'defaultUrl ...

In Angular, I am working on manipulating classes by utilizing the $event parameter within the (click) event

Snippet of HTML code with button functionality <div fxLayout="column"gt; <h4>Click the button to select a service.</h4> <ng-container *ngFor="let service of services;"> <button class="service-button&q ...

The dynamic loading of scripts in Nuxt is causing issues with changing route casings

One of the challenges I faced was creating a vue component to dynamically load scripts for ads and ensure they are removed and reloaded when the route changes. The issue arises when navigating back to the same page after leaving, as the ads stop appearing. ...

Tips for making a scrollable container that allows its contents to overflow without clipping?

Currently working on implementing a horizontal card row for my website with a unique hover effect - the cards lightly rotate and raise on hover. Here is a preview: https://i.sstatic.net/eDQ59.gif To make this row responsive, I added overflow-x: auto; to e ...

Is it possible to switch between different fabricJS canvases seamlessly?

Consider this scenario where I have three canvas elements: <canvas id="c1" width="400" height="300"></canvas> <canvas id="c2" width="400" height="300"></canvas> <canvas ...

Customizing CSS Styles in ASP.NET MVC for Multilingual Websites

We are looking to make our ASP-MVC website multicilingual and support different languages. One challenge I am facing is how to apply distinct style-sheets for each language, especially when dealing with right-to-left (RTL) languages like Hebrew or Arabic c ...

Angular Application for Attaching Files to SOAP Service

I am currently utilizing soap services to pass XML data along with file attachments. While SoapUI tool works perfectly for this purpose, I want to achieve the same functionality through Angular6 in my project. Below is a snippet of my Xml code. <soap ...

Attempting to modify background by manipulating the state in Reactjs

I'm currently working on an app that features various games. My goal is to allow users to click a button and have the game display on the screen, with the background color changing as well. I aim to utilize state to control the overall background of t ...

Invoking the HTML method from a WCF service

Currently, I am utilizing a callback in my WCF service to receive raw frames from the camera. I am currently working on developing an HTML application that will showcase these frames. However, my current approach involves using a button click event in HTM ...

Determining the location of the cursor within 'ng2-ckeditor'

I'm a beginner with Angular 2 and I'm using 'ng2-ckeditor 1.0.7' in my Angular 2 application. The editor is functioning well within the app. However, I am now faced with the challenge of appending text at the cursor position. Unfortunat ...