【问题标题】:Change the property of element inside iframe in angular 2以角度 2 更改 iframe 内元素的属性
【发布时间】:2016-04-09 07:21:23
【问题描述】:

我想在 angular 2 typescript 中更改 iframe 中元素的属性,类似于 javascript 代码

document.getElementById('iframeId').window.document.getElementById('home-grid').style.visibility = "hidden";

我的 Angular 打字稿代码:

var iframe   = document.getElementById('iframeId');
var insideDoc = iframe.contentDocument || iframe.contentWindow.document;

编译代码出错:

stream.js:74
      throw er; // Unhandled stream error in pipe.
      ^
 Error: ./angularapp/web/component/mainPage/mainPage.ts
←[37m(←[39m←[36m35←[39m,←[36m32←[39m): ←[31merror TS2339: Property 'contentDocument' does not exist on type 'HTMLElement'.←[39m./angularapp/web/component/mainPage/mainPage.ts
←[37m(←[39m←[36m35←[39m,←[36m58←[39m): ←[31merror TS2339: Property 'contentWindow' does not exist on type 'HTMLElement'.←[39m

有没有办法在 Angular 2 中实现这一点?请帮忙

【问题讨论】:

  • @Günter Zöchbauer。问题不是提供的链接的副本,因为我的问题是从角度 2 的 iFrame 中获取元素,我没有找到任何类似的链接。如果答案已经可用,请分享它的链接。
  • Angular 没有什么特别之处,和 JavaScript 一样。
  • 但我收到了我的问题中提到的错误。 “‘HTMLElement’类型上不存在属性‘contentWindow’”。我是否有导入任何东西来实现这一目标?
  • 您的代码看起来不像链接问题的已接受答案中的代码。无论如何,您的问题没有提供足够的信息来调试您的问题。如果您表明链接的答案无法解决您的问题,我可以重新提出问题。

标签: iframe angular


【解决方案1】:
@Component({
  selector: 'my-app',
  template:`
    <h1>Selecting Number</h1>
    <iframe id="iframeId" src="iframe.html" (load)="onLoad()"></iframe>
  `,
})
export class App {
  onLoad()  {
    var iframe   = document.getElementById('iframeId');
    var iWindow = iframe.contentWindow
    var doc = iframe.contentDocument || iframe.contentWindow.document;
    console.debug(doc);
    console.log(doc.getElementById('foo').innerText);
  }
}

Plunker demo

【讨论】:

  • 我的文件中有类似的步骤。但我仍然收到上面提到的编译错误。我必须导入任何东西才能得到这个 HTMLElement 吗?
  • 试试var iWindow = (&lt;HTMLIFrameElement&gt;iframe).contentWindow;
  • var iframe = document.getElementById('iframeId'); var doc = (iframe).contentDocument || (iframe).contentWindow.document; console.log("Iframe 返回",iframe); console.log("文档返回", doc); iframe 返回整个文档,而变量 'doc' 返回 null。
  • 由于某种原因,加载事件被触发了两次,有人遇到同样的问题吗?
  • 好,“ionic serve”不工作,“ionic cordova run android -lcs”不工作,因为实时重新加载导致错误,只有“ionic cordova run android”工作。谢谢你的回答,它工作现在给我
猜你喜欢
  • 1970-01-01
  • 2018-08-13
  • 1970-01-01
  • 2021-06-18
  • 1970-01-01
  • 2017-11-10
  • 2012-03-09
  • 2017-10-21
  • 1970-01-01
相关资源
最近更新 更多