首页 > 解决方案 > 如何在具有角度的 iframe 中找到子节点并设置它们的样式?

问题描述

我需要一种方法来找到带有角度的 iframe 内的子节点(我需要 html 元素)。我目前的方法如下所示:

我在 iframe 中放置了一个参考变量(#privacyPolicy)

<iframe
    name="privacy-policy" 
    id="privacy-policy"
    [src]="myURL"
    #privacyPolicy>
</iframe>

在我的组件中,我使用 @ViewChild 来访问我的 iframe

export class MyClass implements AfterViewInit {
  @ViewChild('privacyPolicy', { static: false }) privacyPolicy: ElementRef<any>;

  ngAfterViewInit() {
    const hostElement = this.privacyPolicy.nativeElement;
    console.log(hostElement.children);
    console.log(hostElement.parentNode);
    console.log('iframe', this.privacyPolicy.nativeElement.style.border = '1px solid black');
  }
}

console.log()生命周期中的第三个ngAfterViewInit()正在工作并设置 iframe-Element 的样式。但我想为嵌套在 iframe-Element 中的 html-Element 设置样式。

我已经这样尝试过了(没有成功):

hostElement.children[0].style.border = "1px solid black";

有没有一种干净简单的 Angular 方法来完成这项工作?

标签: javascriptangulartypescriptiframeviewchild

解决方案


您需要访问 contentDocument,然后从 iframe 获得内容 HTML。在你的情况下:

const hostElement = this.privacyPolicy.nativeElement;
hostElement.contentDocument.body.style.border = '1px solid black';

如果您想为 iframe 添加新样式

  const hostElement = this.privacyPolicy.nativeElement;
  const iframe = hostElement.contentDocument;
  const style = document.createElement('style');
  let newStyle = 'body {background-color: red;}';
  style.innerText = newStyle;
  iframe.head.appendChild(style);

推荐阅读