Intento obtener un elemento iframe que tenga una identificación dinámica que se proporcione como atributo @Input() de un componente Angular. Necesito esto porque necesito mostrar una lista de iframe en la misma página, de ahí la identificación única:
Lo que he intentado: https://stackblitz.com/edit/angular-yhdijr
app.component.html :
<div *ngFor="let index of [0, 1, 2]"> <app-iframe [iframeId]="'iframe' + index"></app-iframe> </div> iframe.component.ts :
export class IframeComponent implements OnInit { @Input() iframeId!: string; constructor() {} ngOnInit(): void { console.log('iframeId', this.iframeId); let iframe = document.getElementById(this.iframeId) as HTMLIFrameElement; console.log('iframe', iframe); iframe?.addEventListener('load', () => { console.log('iframe loaded ?'); let iframeWindow = iframe.contentWindow; }); } } iframe.component.ts :
<iframe [id]="iframeId" srcdoc=" <p>Some iframe content</p> " ></iframe>Y el resultado en la consola:
iframeId iframe0 iframe null iframeId iframe1 iframe null iframeId iframe2 iframe null Angular is running in development mode. Call enableProdMode() to enable production mode. iframeId undefined iframe null Angular is running in development mode. Call enableProdMode() to enable production mode.Nota: no sé por qué las tres últimas líneas están aquí, espero que sea solo un error de stackblitz.
Una última cosa que noté es cuando inspeccioné el DOM, el primer iframe tiene una identificación undefined mientras que el segundo y el tercero tienen iframe1 e iframe2 respectivamente.
Entonces, mi pregunta es : ¿cómo puedo obtener la referencia de mi iframe? ¿Es posible con el atributo id si se pasa por @Input() ? Si no, ¿cómo? Pensé en @ViewChild o @ViewChildren pero preferiría el método "id".
Su contenido no está definido porque aún no está cargado. Puede verificar Angular Lifecycle para esto.
En lugar de usar su código en ngOnInit(), intente verificar en ngAfterViewInit() a quien se llama una vez después de ngAfterContentChecked(). Probé tu código stackblitz y funcionó.
Algo como (en su iframe.component.ts):
ngOnInit() {} ngAfterViewInit(): void { console.log('iframeId', this.iframeId); let iframe = document.getElementById(this.iframeId) as HTMLIFrameElement; console.log('iframe', iframe); iframe?.addEventListener('load', () => { console.log('iframe loaded ?'); let iframeWindow = iframe.contentWindow; }); }