Tips for incorporating pre-written CSS code from an ajax request into an Angular 2 application

How can I incorporate CSS text retrieved from the backend into my Angular component?

I attempted to use DomSanitizer's bypassSecurityTrustHtml method, but found that any included style tags were being escaped.

For instance:

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

@Component({
  selector: 'the-app',
  template: `
     <div [innerHtml]="myHtml"></div>
  `,
})
export class App {
  constructor(private sanitizer: DomSanitizer) {
    // The CSS text would typically be fetched from a database...
    this.myHtml = sanitizer.bypassSecurityTrustHtml('<div><style>.myClass{color: red;}</style><div>THIS SHOWS FINE</div></div>') ;
  }
}

Answer №1

This solution seems to be effective for me. However, I am a bit surprised by the inconsistency in how escaping is handled compared to my initial post.

import {Renderer, OnInit} from '@angular/core'
import {BrowserModule, DomSanitizer} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
     <div #myRef></div>
     <div class=".newClass">CHANGE COLOR TO RED</div>
  `,
})
export class AppComponent implements OnInit {
    @ViewChild('myRef') myReference: ElementRef;
    constructor(private renderer: Renderer) {

    }
    ngOnInit() {
        let tempElement = this.renderer.createElement(this.myReference.nativeElement, 'div');
        tempElement.innerHTML = '<style type="text/css">.newClass { color: red;}</style>';

    }
}

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

My postman is successfully uploading image files, but for some reason, my code isn't cooperating. Are there any adjustments that need to be made?

While attempting to upload an image file with form data in Angular, I encountered a discrepancy in behavior between Postman and my project. In Postman, under the headers section, I have configured the following: Content-Type: multipart/form-data, token: ...

Utilize a jQuery ajax request using either the GET or POST method

Similar Question: When is it appropriate to use POST instead of GET? When utilizing a jQuery ajax request to interact with the server, when is it best practice to utilize type get for the call and when is it more suitable to use post? ...

Navigating cross domain JSONP cookies in IE8 to IE10 can be a real headache

For reasons completely out of my control, here is the current scenario I'm faced with: I have a product listing on catalog.org When you click the "Add to Cart" button on a product, it triggers an AJAX JSONP request to secure.com/product/add/[pro ...

Adding a content security policy in Node.js: A Step-by-Step Guide

Does anyone have tips on setting headers for a content security policy? I attempted it in Angular and configured the headers ...

Selenium Webdriver faced challenges in identifying dynamically created scripts using CSS selectors

I am in need of assistance with the following: Requirement: On the homepage, there is a navigation menu bar that changes appearance when scrolling down. This change is reflected in the body class name switching from "home" to "home scriptable persistent-o ...

SEO Friendly URL for JQuery Tabbed Content

I have developed a jQuery powered tabbed content system, where clicking on a tab changes the content below. However, I am facing an SEO issue. The SEO specialist has advised me to make it more SEO-friendly by adding different URLs to each tab. Can anyone ...

Parsing JSON objects, then sanitizing them for secure storage in a database

Hi, I am struggling with sending JSON data to my PHP script and then unpacking, cleaning, and sanitizing it for insertion into a database. The issue arises when trying to get the data to the PHP script and reading it as an undefined index error is thrown. ...

Displaying information on a Rails view

I am a beginner in the world of Rails, so I'm not entirely certain if this is the correct approach to take. Within my view, there is an AJAX link that contains several checkboxes structured like so: <% @row_headers.each do |row_header| %> < ...

The switch switches on yet another switch

Greetings everyone, Currently, I am in the midst of my exam project and creating a mobile menu. The functionality is there, but unfortunately, when closing the menu, it also triggers the search toggle which displays an unwanted div, becoming quite botherso ...

Mastering Relationship Data Display in Views (Tables) with REST API in Spring

I am currently facing an issue with displaying User data in an ajax Datatable that has a many-to-many relationship with Roles. When a User has multiple roles, the Datatable shows [object Object] for each role instead of the actual role name. I'm unsur ...

Issue with AnimeJS Motion Path causing element to deviate from desired SVG path

I'm attempting to use an SVG element and the AnimeJS library to make the orange marker follow the course of this RC car race track. https://i.stack.imgur.com/8FKHC.png Despite my efforts, I am encountering strange and undesirable outcomes. At times ...

Retrieving data from an XML file using an Ajax request

I am using a native AJAX request to insert node values into HTML divs. However, I have noticed that when I update the XML values and upload them to the server while the website is running, Chrome and IE do not immediately reflect the changes (even after re ...

.NET Core Request.Form

I built a view featuring a jQuery datatable bound to server-side data with 3 drop-downs serving as filters. While I used Request.form to fetch the datatable variables (draw, length, start), I encountered an issue in retrieving the values of the 3 drop-down ...

Facing issues using Angular 5 for PUT requests due to 401 errors

When attempting to update data using the PUT Method in my angular service and express routes, I encountered a 401 error. Here is my service code: //401 makeAdmin(_id) { this.loadToken() let headers = new Headers() headers.append('Authorization& ...

Angular 2 form with integrated image functionality

I am currently working on developing a chat application using Angular 2 and I am facing an issue with displaying Emojis in the input field. Unfortunately, HTML does not support images in input fields. I have attempted the following approach, but it did n ...

"Effortlessly deleting data with AJAX in jQuery: A step-by-step guide

I am having an issue with deleting a comment using ajax in CodeIgniter. When I click the button, the comment gets successfully deleted from the database. However, I encounter an error with the jQuery remove function: Uncaught TypeError: Cannot read proper ...

Attach a click event listener to content loaded through AJAX using only JavaScript, without relying on jQuery

I'm curious about how to attach a click event to an element that will be added later through an ajax call. I know jQuery can handle this like so: $(document).on('click', '.ajax-loaded-element' function(){}); However, I'm not ...

What steps can be taken to enhance the efficiency of this jQuery search implementation?

I have this code snippet here that is functioning well, but it tends to freeze up if I type too quickly. I am eager to enhance its performance. This code is designed to search a MySql table and retrieve results based on criteria from various columns. < ...

Strategies for avoiding overflow-x issues in Safari and mobile devices

I am currently facing an issue where I have a div containing a table with overflow enabled, allowing the whole table to be viewed by scrolling. However, on Safari and mobile Safari browsers, there is a horizontal scroll on the html and body elements. Whil ...

Utilizing media queries for responsive design in CSS

I've been working on aligning the page content for different browser sizes using CSS. However, I'm having an issue with the first @media statement - no matter what changes I make in there, it doesn't affect the layout. I've been using ...