0

I am Creating a iframe Dynamically in Angular in ngOninit.

  ngOnInit(){
      const el = document.createElement('iframe');
      el.setAttribute('sandbox', '');
    }

And then using ElementRef in ngAfterViewInit i am trying to access the dynamically created component.

this.elRef.nativeElement.querySelector('iframe');

But if gives me null always , how to get the reference of the element here, i even tried with afterContentInit nothing works.

INFOSYS
  • 1,465
  • 9
  • 23
  • 50
  • Try to wrap this call into `setTimeout` with 1 sec delay, if it works, you should be able to keep this call inside empty `setTimeout`. – P.S. Jun 14 '18 at 21:20
  • i did try using SetTimeout also dosent work @CommercialSuicide – INFOSYS Jun 14 '18 at 21:21
  • In provided code i see, that you create element and set attribute, but do you include this element to DOM? Do you see this iframe in inspector? – P.S. Jun 14 '18 at 21:23
  • Yes it get added to the DOM i can see it in my browser window – INFOSYS Jun 14 '18 at 21:24
  • You need to attach `el` to something in the component's template, e.g `const outerDiv = this.elRef.nativeElement.getElementsByTagName('div')[0];` then `outerDiv.appendChild(el);` –  Jun 15 '18 at 00:56
  • @eric99 i can see the iframe but i cannot access it after view init – INFOSYS Jun 15 '18 at 09:28
  • I think `document.createElement()` puts it on the DOM (therefore you can see it), but it is outside of the elRef - so I suggest appending it to something in your Angular template. –  Jun 15 '18 at 09:38
  • @eric99 yes i think you are right but using this creates 2 iframes in the view i donot know why ? – INFOSYS Jun 15 '18 at 09:42
  • Instead of `outerDiv.appendChild(el);` try `outerDiv.createElement('iframe');` –  Jun 15 '18 at 09:45
  • it says create element is not a function – INFOSYS Jun 15 '18 at 09:46
  • I think we are on the right track. Take a look at [this question](https://stackoverflow.com/questions/36847752/how-to-use-document-createelement-without-defining-a-variable) and see if you can make use of the examples. I'll take a further look later on. –  Jun 15 '18 at 09:51

0 Answers0