Skip to content

Instantly share code, notes, and snippets.

@voznik
Forked from drakkein/iframeResizer.directive.ts
Created December 17, 2018 10:55
Show Gist options
  • Save voznik/d6e5698e6e7af14c00f965c2ea61bd33 to your computer and use it in GitHub Desktop.
Save voznik/d6e5698e6e7af14c00f965c2ea61bd33 to your computer and use it in GitHub Desktop.
iframe resizer directive for Angular 4 (No CORS)
import { Directive, ElementRef, OnDestroy, OnInit, Renderer2 } from '@angular/core';
@Directive({
selector: '[iframeResize]',
})
export class IframeResizeDirective implements OnInit, OnDestroy {
private listener: () => void;
private observer: MutationObserver;
get element() {
return this.elementRef.nativeElement;
}
get contentHeight() {
return this.element.contentDocument.body.scrollHeight;
}
constructor(private elementRef: ElementRef, private renderer: Renderer2) {}
ngOnInit() {
this.listener = this.renderer.listen(this.element, 'load', () => {
this.setFrameHeight(this.contentHeight);
this.observer = new MutationObserver((mutations) => {
console.log('Mutation happened');
this.setFrameHeight(this.contentHeight);
});
this.observer.observe(this.element.contentDocument.body, {
attributes: true,
childList: true,
characterData: true,
subtree: true
});
});
}
setFrameHeight(height: number) {
this.renderer.setStyle(
this.element,
'height',
`${height}px`
);
}
ngOnDestroy() {
this.observer.disconnect();
this.listener();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment