首页 文章

Angular 2/4:将编译的组件添加到iframe

提问于
浏览
2

我有一个新的Angular应用程序(可以使用v 2.4.10或4.0.0-rc.5),它使用iframe嵌入一些预先存在的内容 . 使用iframe加载时调用的方法 - (load)="processIframe(extFrame)" - 我可以通过Angular Renderer设置监听器,并获取对子DOM元素的引用(this answer帮助了该过程) .

通过替换 innerHtml ,可以很容易地在iframe中设置元素的内容 . 但是,我需要做的是用编译的Angular组件替换这个html . 该组件通过服务从API中获取一些数据 .

有没有办法用编译的组件替换iframe中的DOM元素内容?

1 回答

  • 9

    您可以创建 ComponentRef 实例,然后将其 compRef.location.nativeElement 插入所需位置 .

    我会这样做 Plunker Example

    @Component({
      selector: 'my-app',
      template: `
        <button (click)="createComponent()">Create component</button>
        <iframe #iframe (load)="onLoad()></iframe>
      `,
    })
    export class App {
      @ViewChild('iframe') iframe: ElementRef;
    
      doc: any;
      compRef: ComponentRef<DynamicComponent>;
    
      constructor(
        private vcRef: ViewContainerRef,
        private resolver: ComponentFactoryResolver) {}
    
    
      createComponent() {
        const compFactory = this.resolver.resolveComponentFactory(DynamicComponent);
        this.compRef = this.vcRef.createComponent(compFactory);
    
        this.doc.body.appendChild(this.compRef.location.nativeElement);
      }
    
      onLoad() {
        this.doc = this.iframe.nativeElement.contentDocument || 
                   this.iframe.nativeElement.contentWindow;
      }
    
      ngAfterViewInit() {
        this.onLoad(); // in Firefox state is uninitialized while 
                       // in Chrome is complete so i use `load` event for Firefox
      }
    
      ngOnDestroy() {
        if(this.compRef) {
          this.compRef.destroy();
        }
      }
    }
    

    不要忘记将 DynamicComponent 添加到`entryComponents数组中

相关问题