【问题标题】:Angular: Component scss styles not applied to tags supplied to [innerHTML] of div?Angular:组件scss样式不适用于提供给div的[innerHTML]的标签?
【发布时间】:2022-01-20 04:30:32
【问题描述】:

我有一个 MatDialog,它在构建时由其父级提供一个 HTML 字符串。 HTML 字符串是命名 div 内容的来源,包含嵌入在 html 中的 <table> 标签,但由于某种原因,对话框的 scss 文件中定义的表格样式不适用于我指定为 [innerHTML] 的字符串,虽然它适用于直接硬编码到 html 文件中的 <table> 标签。

有什么方法可以让对话框使用对话框组件的样式模板中包含的样式来呈现 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:

    <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:

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

【问题讨论】:

    标签: javascript css angular angular-material mat-dialog


    【解决方案1】:

    您应该禁用该组件的封装。你可以这样做:

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

    【讨论】:

      【解决方案2】:

      将 ViewEncapsulation 与组件一起导入:

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

      并在装饰器中为组件设置封装,以及选择器、模板、css 样式等:

      encapsulation: ViewEncapsulation.None
      

      例如:

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

      【讨论】: