如何在带有角度的 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');
}
}

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

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

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

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

您需要访问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);

最新更新