iframe 不使用 srcdoc 属性加载样式

cda*_*lto 5 html javascript css iframe angular

iframe在 Angular 组件中使用 an ,并且在使用该src属性加载站点时,样式和内容非常好。当尝试使用该属性将静态 html 作为字符串加载时srcdoc,似乎只有 HTML 正在呈现。以下是一个非常基本的示例,我已将其简化为仍然不加载样式。

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

@Component({
  selector: 'app-newsletter-viewer',
  templateUrl: './newsletter-viewer.component.html',
  styleUrls: ['./newsletter-viewer.component.scss'],
  encapsulation: ViewEncapsulation.ShadowDom
})
export class NewsletterViewerComponent implements OnInit {
  newsletterSrcDoc: string;
  constructor() {}

  ngOnInit() {
    this.newsletterSrcDoc = `
    <!DOCTYPE html>
    <html>
      <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css" />
    <style>
    p {
    color: red;
    font-size: 2em;
    }
    </style>
      </head>
      <body>
        <div class="page">
        <div id="template2">
        <div class="section-cover-photo">
        <div class="col">
        <div class="container">
          <img src="" class="cover-photo">
        <div class="banner-template2">
          <h1>Test Title</h1>
          <p>This is a test document.</p>
        </div>
        </div>
        </div>
        </div>
        </div>
        </div>
      </body>
    </html>
    `;
  }

}
Run Code Online (Sandbox Code Playgroud)
.wrap {
  width: 170px;
  height: 220px;
  padding: 0;
  overflow: hidden;
}

.frame {
  width: 8.5in;
  height: 11in;
  border: 0;
  -ms-transform: scale(0.25);
  -moz-transform: scale(0.25);
  -o-transform: scale(0.25);
  -webkit-transform: scale(0.25);
  transform: scale(0.25);
  -ms-transform-origin: 0 0;
  -moz-transform-origin: 0 0;
  -o-transform-origin: 0 0;
  -webkit-transform-origin: 0 0;
  transform-origin: 0 0;
}
Run Code Online (Sandbox Code Playgroud)
<div class="wrap">
  <iframe class="frame" [srcdoc]="newsletterSrcDoc"></iframe>
</div>
Run Code Online (Sandbox Code Playgroud)

cda*_*lto 4

在采用不同的方法在 Stack Overflow 上搜索相关主题后,该主题的公认答案似乎对我有用:iframe inside angular2 component, Property 'contentWindow' does not exit on type 'HTMLElement'

据我所知,这个问题与 Angular 选择如何/何时在 iframe 中渲染 DOM 有关。如果iframe的文档内容是在View(特别是View中的)初始化之后渲染的,那么网页上完整的DOM结构中就不再省略iframeiframe的标签了。<head>