Angular 2/4:将编译的组件添加到iframe [英] Angular 2/4: Add compiled component to an iframe

查看:717
本文介绍了Angular 2/4:将编译的组件添加到iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a new Angular app (can use v 2.4.10 or 4.0.0-rc.5), which uses an iframe to embed some pre-existing content. Using a method called when the iframe loads -- (load)="processIframe(extFrame)" -- I'm able to set up listeners via the Angular Renderer, and to grab references to child DOM elements (this answer helped with that process).

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

It's easy enough to set the content of an element in the iframe by replacing its innerHtml. However, what I need to do is the replace this html with a compiled Angular component. This component grabs some data from an API via a service.

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

Is there a way to replace DOM element content in the iframe with the compiled component?

推荐答案

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

You can create ComponentRef instance and then insert its compRef.location.nativeElement in desired place.

我会这样做 Plunker示例

I would do it as follows 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数组

Don't forget to add DynamicComponent to `entryComponents array

这篇关于Angular 2/4:将编译的组件添加到iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆