Home  >  Article  >  Web Front-end  >  How to Apply Styles to InnerHTML in Angular?

How to Apply Styles to InnerHTML in Angular?

Barbara Streisand
Barbara StreisandOriginal
2024-10-28 05:17:30379browse

How to Apply Styles to InnerHTML in Angular?

Styling InnerHTML in Angular

When setting innerHTML in Angular, you may encounter an issue where styles are not applied properly. This is due to Angular's encapsulation mechanism, which by default prevents styles from being inherited by the innerHTML content.

To resolve this, you can change the encapsulation property of your component to "None". This allows styles defined in the component to be applied to the innerHTML content.

Here's how to do it:

<code class="typescript">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>';
  }
}</code>

By setting the encapsulation to "None", you can define styles anywhere in your component or in separate CSS files, and Angular will automatically add them to the DOM when rendering the innerHTML content.

The above is the detailed content of How to Apply Styles 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