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

4
我有一个新的Angular应用(可以使用v 2.4.10或4.0.0-rc.5),它使用一个iframe来嵌入一些现有内容。当iframe加载时,通过一个被称为(load)="processIframe(extFrame)" 的方法,我能够通过Angular渲染器设置监听器,并获取子DOM元素的引用 (这个答案 帮助我完成了这个过程)。
通过替换其innerHtml,很容易设置iframe中元素的内容。然而,我需要做的是将这个HTML替换为已编译的Angular组件。 这个组件通过服务从API获取一些数据。
有没有一种方法可以用编译好的组件替换iframe中的DOM元素内容?

你需要解决Angular 2.4.10或4.0.0-rc.5的问题吗?你是否接受更新版本,例如4.1.3? - andreim
我不知道你如何直接将你创建的组件添加到另一个文档(iframe)中。你是否可以接受另一种解决方案,例如在iframe中加载单独的路由,并在主文档和iframe文档之间通信以加载具有特定数据的组件以及可能出现的任何更改?我没有看到其他的方法。 - andreim
@paqogomez 是的,它确实会。另一个DOM,另一个应用程序实例。但是,如果应用程序没有提前加载所有资源并且使用异步加载(请参见路由loadChildren属性),那么就没问题了。 - andreim
@andreim 我选择将我的代码放在路由的守卫中,这对我正在做的事情似乎很有效,但与 OP 不同。如果您想尽可能地回答,我会给您奖励。 - crthompson
@Fiona,针对你的情况,为什么不直接制作一个组件来加载数据,而不是使用iframe呢? - crthompson
显示剩余4条评论
1个回答

16
你可以创建一个 ComponentRef 实例,然后将其 compRef.location.nativeElement 插入到所需的位置。
我会按照以下方式进行操作Plunker 示例:
@Component({
  selector: 'my-app',
  template: `
    <button (click)="createComponent()">Create component</button>
    <iframe #iframe (load)="onLoad()"></iframe>
  `,
})
export class App implements AfterViewInit, OnDestroy {
  @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`数组中


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接