Skip to content

Instantly share code, notes, and snippets.

@mattstabeler
Last active August 21, 2018 17:46
Show Gist options
  • Save mattstabeler/48c6f071e4d38b654ff784f6b29d1fc1 to your computer and use it in GitHub Desktop.
Save mattstabeler/48c6f071e4d38b654ff784f6b29d1fc1 to your computer and use it in GitHub Desktop.
iFrame resizer (consumer) for angular 2
// add this directive to an iFrame element and pass a name of the source, and this will change the height based on the
// events passed from the iframe source. the name of the source, and type of the message are checked before making a
// change to the element width.
// expects an object like to have been sent through the window.postMessage() interface :
// {
// type: 'resize',
// source: 'some-iframe-content',
// value: {
// height: 200
// }
// }
// <iframe src="some-iframe.html" iframe-resizer="some-iframe-content"></iframe>
import { Directive, OnDestroy, HostListener, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[iframe-resizer]'
})
export class IFrameResizerDirective implements OnDestroy {
@Input('iframe-resizer') sourceName: string;
constructor(private el: ElementRef) { }
@HostListener('window:message', ['$event'])
onMessage(event: any) {
if ('undefined' !== typeof event.data &&
'undefined' !== typeof event.data.type &&
event.data.type === 'resize' &&
'undefined' !== typeof event.data.source &&
event.data.source === this.sourceName) {
this.resizeIframe(event.data);
}
}
resizeIframe(data) {
if ('undefined' !== typeof data.value && 'undefined' !== typeof data.value.height) {
if (this.el.nativeElement.clientHeight !== Number(data.value.height)) {
this.el.nativeElement.style.height = data.value.height + 'px';
}
}
}
ngOnDestroy() {
// TODO: destroy @HostListener watcher?
}
}
@benisson
Copy link

benisson commented May 8, 2017

Is this directive to be used with the IFrame Resize lib?
Can you give me an example of how to use it?
thank you so much

@mistrynilesh440
Copy link

Can some one post how to use this directive ?
Thanks.

@bhawin-boom
Copy link

Will this work for multiple iframes on one page . I mean won't it give the heights of multiple iframes on window:message event and you will have to filter out the height with the id of the iframe.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment