Home  >  Article  >  Web Front-end  >  Why Are Styles Not Applied to InnerHTML in Angular?

Why Are Styles Not Applied to InnerHTML in Angular?

Barbara Streisand
Barbara StreisandOriginal
2024-10-27 14:35:02795browse

Why Are Styles Not Applied to InnerHTML in Angular?

Styles Not Working for innerHTML in Angular

Problem Statement:

When passing HTML code as innerHTML to a view, styles defined within the code are not being applied. If the HTML code does not include any inline styles, it displays correctly. However, when inline styles, such as background-color, are added to the HTML code, they are ignored.

Root Cause:

This behavior is a result of Angular's default component encapsulation being set to "Emulated." Emulated encapsulation prevents CSS styles from influencing elements both inside and outside of the component.

Solution:

To allow styles defined within innerHTML to be applied, the component's encapsulation must be changed to "None." This can be achieved by adding the following additional code to the app:

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>';
  }
}

With encapsulation set to "None," styles defined within innerHTML will be added to the DOM automatically, allowing them to be applied to the elements created by the HTML code.

The above is the detailed content of Why Are Styles Not Applied to InnerHTML in Angular?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn