Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 iframe confusion

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:

component.html

<iframe #iframe src="assets/test.html"></iframe>

test.html

<h1 id="wow">Wow</h1>

working typescript (prints <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"));
    }
}

non-working typescript (prints null)

export class MyComponent implements AfterViewInit {

    @ViewChild('iframe') iframe: ElementRef;

    ngAfterViewInit() {
        var doc = this.iframe.nativeElement.contentDocument;
        console.log(doc.getElementById("wow"));
    }
}

Question

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.

like image 564
Jaron Thatcher Avatar asked Feb 28 '17 20:02

Jaron Thatcher


1 Answers

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.

like image 124
Hikmat G. Avatar answered Nov 13 '22 04:11

Hikmat G.