2016-07-19 9 views
6

Ich habe einen iframe innerhalb einer angular2 Komponente, und ich versuche den Inhalt des iframes durch Zugriff auf das contentWindow zu ändern.
Der Iframe sollte eine einfache Schaltfläche enthalten.iframe in angular2 Komponente, Property 'contentWindow' existiert nicht im Typ 'HTMLElement'

Mein Code:

import { Component } from '@angular/core'; 
    @Component({ 
     moduleId: module.id, 
     selector: 'component-iframe', 
     template: '<iframe id="iframe"></iframe>' 
    }) 
    export class ComponentIframe { 
     constructor() { 
     let iframe = document.getElementById('iframe'); 
     let content = '<button id="button" class="button" >My button </button>'; 
     let doc = iframe.contentDocument || iframe.contentWindow; 
     doc.open(); 
     doc.write(content); 
     doc.close(); 
    } 
    } 

Wenn ich die Konstrukteurs-Code und starten Sie die App kommentieren, kompiliert und ordnungsgemäß ausgeführt wird. Dann kommst du auf Kommentar und alles läuft perfekt (der Button ist im iframe vorhanden).

Wenn ich decomment der Code dann die App (NPM Start) beginnen Ich habe die Erstellung Bugs mit der Meldung:

Property 'contentWindow' existiert nicht auf Typ 'Htmlelement'

.

Ich habe auch die Alternative versucht, den Code des Costruktors in ngOnInit(), ngAfterContentInit(), ngAfterViewInit() zu setzen, aber der Fehler bleibt bestehen.

Antwort

12

Die Vorlage noch nicht im DOM existiert, wenn der Konstruktor

Verwendung ausgeführt wird stattdessen

import { Component, ViewChild, ElementRef } from '@angular/core'; 
@Component({ 
    moduleId: module.id, 
    selector: 'component-iframe', 
    template: '<iframe #iframe></iframe>' 
}) 
export class ComponentIframe { 
    @ViewChild('iframe') iframe: ElementRef; 

    ngAfterViewInit() { 
    let content = '<button id="button" class="button" >My button </button>'; 
    let doc = this.iframe.nativeElement.contentDocument || this.iframe.nativeElement.contentWindow; 
    doc.open(); 
    doc.write(content); 
    doc.close(); 
    } 
} 
1

Wenn der Inhalt des IFRAME dann vom gleichen Ursprung erstellt I würde vorschlagen, das IFRAME-Attribut srcDoc zu verwenden, um Inhalt in IFRAME festzulegen und zu ändern.

@Component({ 
    selector: 'my-app', 
    template: ` 
    <p><label for="text">Write content here...</label></p> 
    <textarea 
     #text 
     rows="10" 
     cols="47" 
     placeholder="Write some HTML content here..." 
     [(ngModel)]="srcDocContent"></textarea> 

    <p>Preview HTML content in IFRAME</p> 
    <iframe 
     sandbox="allow-same-origin" 
     [attr.srcDoc]="srcDocContent"></iframe> 
    ` 
}) 
export class App { 

    srcDocContent:string 

    constructor() { 
    this.srcDocContent='Some <strong>HTML</strong> content here...' 
    } 
} 

Sehen Sie diese PLUNKER DEMO

Dadurch werden die nativen HTML-Elemente unberührt bleiben kompatibel mit kantigem Universelles lassen.