Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
108
rated 0 times [  109] [ 1]  / answers: 1 / hits: 16064  / 7 Years ago, tue, february 28, 2017, 12:00:00

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.


More From » html

 Answers
2

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.


[#58731] Monday, February 27, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lamarmaximiliand

Total Points: 388
Total Questions: 104
Total Answers: 104

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
;