简体   繁体   English

Angular:组件 scss styles 不适用于提供给 div 的 [innerHTML] 的标签?

[英]Angular: Component scss styles not applied to tags supplied to [innerHTML] of div?

I've got a MatDialog which is supplied with an HTML string by its parent when it's constructed.我有一个 MatDialog,它在构建时由其父级提供 HTML 字符串。 The HTML string is the source of a named div's content, and contains <table> tags embedded within the html, but for some reason the table style defined in the dialog's scss file isn't applied to the string I specify as [innerHTML] , although it works fine for <table> tags hard-coded directly into the html file. HTML 字符串是命名 div 内容的来源,并包含嵌入在 html 中的<table>标记,但由于某种原因,对话框的 scss 文件中定义的表格样式未应用于我指定为[innerHTML]的字符串,虽然它适用于直接硬编码到 html 文件中的<table>标签。

Is there some way I can get the dialog to render the innerHTML with styles contained in the styles template for the dialog componenet?有什么方法可以让对话框使用对话框组件的 styles 模板中包含的 styles 来呈现 innerHTML?

    export class DialogAgreementViewer implements AfterViewInit {
      constructor(public dialogRef:
        MatDialogRef<DialogAgreementViewer>, @Inject
        (MAT_DIALOG_DATA) public data: string, protected _sanitizer : DomSanitizer){
          this.agreementText = this._sanitizer.bypassSecurityTrustHtml(data);
        }
      public agreementText : SafeHtml;
      @ViewChild('agreementText') agreementTextCtl : ElementRef;
    }

HTML: HTML:

    <p>Agreement Template</p>
    <table>.          <-- Defined table styles are applied to this table.
        <tbody>
            <tr><td>Title</td><td>Name of Work</td></tr>
        </tbody>
    </table>
    
    <div [innerHTML]='agreementText'></div> <-- Table styles not applied here.

SCSS: SCSS:

    table, td {
        border: 1px solid black;
       
    }
    table {
        border-collapse: collapse;
        width: 75%
    }

Import ViewEncapsulation along with Component:与组件一起导入 ViewEncapsulation:

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

and set encapsulation for the component in the decorator, along with selector, template, css styles etc:并在装饰器中设置组件的封装,以及选择器、模板、css styles 等:

encapsulation: ViewEncapsulation.None

For example:例如:

@Component({
  selector: 'your-app',
  templateUrl: './your.component.html',
  styleUrls: ['./your.component.css'],
  encapsulation: ViewEncapsulation.None, // <---------
})

You should disable encapsulation for that component.您应该禁用该组件的封装。 You can do it like this:你可以这样做:

import { Component, ViewEncapsulation } from '@angular/core';
...
@Component({
  ...
  encapsulation: ViewEncapsulation.None,
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM