I am attempting to change the value of an element inside of an iframe in Angular 2. I have tried many things, but am continuously unable to reference an item using getElementById(). I have a test scenario which works in one case, and not another, which is serving to confuse me even further:
<iframe #iframe src="assets/test.html"></iframe>
<h1 id="wow">Wow</h1>
<h1 id="wow">Wow<h1>)export class MyComponent implements AfterViewInit {
    @ViewChild('iframe') iframe: ElementRef;
    ngAfterViewInit() {
        var doc = this.iframe.nativeElement.contentDocument;
        doc.open();
        doc.write('<h1 id="wow">Wow</h1>');
        doc.close();
        console.log(doc.getElementById("wow"));
    }
}
null)export class MyComponent implements AfterViewInit {
    @ViewChild('iframe') iframe: ElementRef;
    ngAfterViewInit() {
        var doc = this.iframe.nativeElement.contentDocument;
        console.log(doc.getElementById("wow"));
    }
}
How in the world can I get the second one to properly print the element? No matter what I do or what I put in test.html, it is always null.
Inside ngAfterViewInit(), it's likely that test.html hasn't been loaded into iframe yet.
This can be subverted using the (load)="yourLoadFunction()" directive on your iframe like <iframe (load)="yourLoadFunction()"></iframe>
If you then move the code from ngAfterViewInit() into yourLoadFunction(), it should work correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With