Angular: How to apply component CSS to dynamically injected HTML from an API?

Discussão em 'Angular' iniciado por panagiotis lymperopoulos, Fevereiro 25, 2025.

  1. I am receiving an HTML string from an API response and need to render it inside my Angular component while keeping the component's CSS styles applied.

    What I have tried:

    Using [innerHTML], but the styles defined in my component's SCSS are not applied:

    <div class="content" [innerHTML]="htmlContent"></div>

    .content h3 {
    color: red; // This does NOT apply
    }


    Using DomSanitizer to bypass security restrictions:

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

    htmlContent: SafeHtml;

    constructor(private sanitizer: DomSanitizer) {}

    ngOnInit() {
    this.htmlContent = this.sanitizer.bypassSecurityTrustHtml(apiResponseHtml);
    }


    But the styles from the component still do not apply.

    Trying ::ng-deep .content h3 { color: red; }, but I want to avoid ::ng-deep since it's deprecated.

    Setting ViewEncapsulation.None in my component, but this makes the styles global, which I don’t want.

    Question: How can I render the API-provided HTML inside my component while keeping the component's scoped CSS applied?

    I tried using [innerHTML] to inject the HTML string, expecting it to apply the component's scoped CSS, but it didn't work. I also tried DomSanitizer, ::ng-deep, and ViewEncapsulation.None, but none of them gave the expected result. The styles from my component are not applied to the dynamically inserted HTML. I need a solution that keeps the CSS scoped while applying it to the injected content.

    Continue reading...

Compartilhe esta Página