Angular 2/4: Add compiled component to an iframe

后端 未结 1 1342
轮回少年
轮回少年 2020-12-28 11:11

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 -- (loa

1条回答
  •  执笔经年
    2020-12-28 11:47

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

    I would do it as follows Plunker Example:

    @Component({
      selector: 'my-app',
      template: `
        
        
      `,
    })
    export class App implements AfterViewInit, OnDestroy {
      @ViewChild('iframe') iframe: ElementRef;
    
      doc: any;
      compRef: ComponentRef;
    
      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();
        }
      }
    }
    

    Don't forget to add DynamicComponent to `entryComponents array

    0 讨论(0)
提交回复
热议问题