加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

typescript – 在Angular 6中渲染iframe内部的视图并继续使用模

发布时间:2020-12-17 17:37:18 所属栏目:安全 来源:网络整理
导读:在angularJS中,您可以使用$compile在iframe中呈现视图,并将 angularjs $scope变量保留在iframe中. Angular.IO中是否有相同的功能? AngularJS在指令中等效: var $body = angular.element($element[0].contentDocument.body);var template = $compile(conten
在angularJS中,您可以使用$compile在iframe中呈现视图,并将 angularjs $scope变量保留在iframe中. Angular.IO中是否有相同的功能?

AngularJS在指令中等效:

var $body = angular.element($element[0].contentDocument.body);
var template = $compile(contents)($scope);
$body.append(template);

我想渲染一个iframe,传递必要的html来填充iframe,并能够在iframe html中使用模板语言.

与此类似,但this plunkr无效.它不会在iframe视图中呈现变量.

更新:找到一些关于如何在打字稿中使用angularJS的教程,这可能有用.最后,我想在父和iframe之间共享变量,类似于在parent和iframe之间共享angularJS中的$scope.

解决方法

您可以获取iframe窗口并从Angular组件中注入一个变量,您可以注入一个Subject,这样您就可以在iframe中触发更改( FULL DEMO),如下所示:

这是模板组件

<hello name="{{ name }}"></hello>
<button (click)="sendData()">Click Here</button>
<iframe #iframe frameborder="1" width="100%" height="50%"></iframe>

这是逻辑:

import { Component,ViewChild,ElementRef,OnInit } from '@angular/core';
import { Subject } from 'rxjs/Subject';

const iframeCode = `
  <h1>Hello World</h1>

  <script type="text/javascript">
    if (dataFromParent) {
      // Subscribe to the Subject so you can trigger changes from Angular
      dataFromParent.subscribe(res => {
        document.querySelector('h1').innerHTML = res;
      })
    }
  </script>
`

@Component({
  selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  data$: Subject<string> = new Subject('');
  @ViewChild('iframe') iframe: ElementRef;

  name = 'Angular';

  ngOnInit() {
    this.setIframeReady(this.iframe);
  }

  sendData() {
    this.data$.next('From parent to iframe');
  }

  private setIframeReady(iframe: ElementRef): void {
    const win: Window = iframe.nativeElement.contentWindow;

    // Pass the variable from parent to iframe
    win['dataFromParent'] = this.data$;

    const doc: Document = win.document;
    doc.open();
    doc.write(iframeCode);
    doc.close()
  }
}

此外,如果您想从iframe与父级进行通信,则可以使用CustomEvent.

希望它有所帮助.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读