在Angular 6中渲染iframe内部的视图并继续使用模板变量

Tim*_*yce 5 iframe typescript angular6

在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);
Run Code Online (Sandbox Code Playgroud)

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

与此相似但是,这个plunkr不起作用.它不会在iframe视图中呈现变量.

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

小智 7

您可以获取iframe Window并从Angular组件中注入变量,您可以注入a,Subject以便可以在iframe中触发更改(FULL DEMO),如下所示:

这是模板组件

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

这是逻辑:

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()
  }
}
Run Code Online (Sandbox Code Playgroud)

另外,如果您希望从iframe与父级进行通信,则可以使用CustomEvent

希望对您有所帮助。