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