在 Angular 中将样式应用到innerHTML

问题描述 投票:0回答:1

我有一个名为ExternalHtmlComponent的Angular组件,负责渲染从后端获取的HTML内容。使用 [innerHTML] 属性绑定将 HTML 内容动态插入到元素中。为了设置动态插入的 HTML 内容的样式,我在 Components/external-html.scss 文件中定义了一个名为 external-html 的 mixin。但是这些样式不适用于标签。

如何确保 external-html.scss 中定义的所有样式都正确应用于动态插入的 html 中相应的 HTML 元素?

components/external/external_html.component.ts

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

@Component({
  selector: 'component-external-html',
  template: '<div [innerHTML]="html"> </div>',
  styleUrls: ['./external-html.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class ExternalHtmlComponent {

  @Input() html: string;

  constructor() { }

}

components/external/external_html.component.scss

@import "components/external-html";

:host {
  @include external-html;
}

components/external-html.scss

@mixin external-html {
    font: var(--font-body);
    color: var(--color-text); // only these changes are applied, when inspected.
    // if I add background color here, <a> tags gets it.

    h1 {
        font: var(--font-subtitle);
    }
    
    h2 {
        font: var(--font-label-bold);
        text-transform: uppercase;
        color: var(--color-secondary);
    }
    
    h3 {
        font: var(--font-emphasis);
    }
    
    b, strong {
        font: var(--font-body-semibold);
        background-color: red;
    }
    
    a {
        font: var(--font-body-semibold);
        color: var(--color-primary);
        text-decoration: underline;
    }
    
    blockquote {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        padding: var(--spacing-2);
        border-radius: var(--border-radius-2);
        background-color: var(--color-primary-05);
    }
}

它的用法如下:

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

@Component({
  selector: 'app-external-html-example',
  template: '<component-external-html [innerHTML]="exampleHtmlContent"></component-external-html>',
})
export class ExternalHtmlExampleComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  public exampleHtmlContent: string = `
  <h1>This is a Heading 1</h1>
  <h2>This is a Heading 2</h2>
  <h3>This is a Heading 3</h3>
  <p>This is a paragraph with <b>bold</b> text.</p>
  <a href="#">This is a link</a>
  <ul>
    <li>Unordered list item 1</li>
    <li>Unordered list item 2</li>
  </ul>
  <ol>
    <li>Ordered list item 1</li>
    <li>Ordered list item 2</li>
  </ol>
  <blockquote>
    This is a blockquote with background color, padding, and rounded corners.
  </blockquote>
`;

}

javascript html angular sass
1个回答
0
投票

我发现一个问题,您需要在下面的行中传递

[html]
而不是
[innerHTML]

...
@Component({
  selector: 'app-external-html-example',
  template: '<component-external-html [html]="exampleHtmlContent"></component-external-html>',
})
...

[innerHTML]
主要破坏了组件,因此样式没有得到应用是我的理论!

© www.soinside.com 2019 - 2024. All rights reserved.