Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style not working for innerHTML in Angular [duplicate]

Tags:

html

css

angular

People also ask

How do I give innerHTML a style?

Within HTML elements, there are three ways you can insert CSS into an HTML document. Inline – to use an inline style attribute. – within the /head/ section using an *style].

Why innerHTML does not work?

People can struggle and complain about innerHTML not working. Such things usually occur because of human error, when strings are not appropriately defined, or there are some mistakes in JavaScript code.

Can we use innerHTML in angular?

Angular 2+ supports an [innerHTML] property binding that will render HTML. If you were to otherwise use interpolation, it would be treated as a string. In this article, you will be presented with how to use [innerHTML] and some considerations for usage.

What method is used to replace the innerHTML of an element?

To replace innerHTML of a div tag, use the html() method. The dot notation calls the html() method to replace the inner html with the parameter placed between, i.e. Demo here.


This behavior you're getting is normal. The class added to innerHTML is ignored because by default the encapsulation is Emulated. Which means Angular prevents styles from intercepting inside and outside of the component. You should change the encapsulation to None in your component. This way, you'll be able to define classes wherever you want: inside styles or in a separate .css, .scss or .less style-sheet (it doesn't matter) and Angular will add them to the DOM automatically.

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'example',
  styles: ['.demo {background-color: blue}'],
  template: '<div [innerHTML]="someHtmlCode"></div>',
  encapsulation: ViewEncapsulation.None,
})
export class Example {
  private someHtmlCode = '';

  constructor() {
    this.someHtmlCode = '<div class="demo"><b>This is my HTML.</b></div>';
  }
}

I was also facing the same issue but after reading this below link I figured out the solution and it was done without using pipes

Hope this will help you.

https://netbasal.com/angular-2-security-the-domsanitizer-service-2202c83bd90