如何使用角度4从iframe调用组件功能

时间:2017-12-05 14:04:44

标签: angular iframe

我用来在angular4应用程序中显示iframe,即localhost:4201。 iframe页面来自localhost:9000。在我的iframe页面中有一个按钮。如果我点击按钮,需要执行我的angular4组件功能。我尝试了这个,但它抛出了错误

localhost:9000 - index.html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>sampleMyHtmlApp</title>
</head>
<body>
    <div style="padding: 20px 0px;">
        <div class="container">
            <form class="form-horizontal">
                <div class="form-group">
                    <label class="control-label col-xs-2">Account Number</label>
                    <div class="col-xs-10">
                        <input type="text" class="form-control" id="inputAccountNo" placeholder="Account number">
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-xs-offset-2 col-xs-10">
                        <button type="submit" class="btn btn-primary" onClick='parent.SampleFunction()'>Action</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</body>
</html>

本地主机:4201

app.component.html

<iframe width="100%" [src]="url | safe" style="height: 302px; border: none;"></iframe>

app.component.ts

import { Component, Input } from '@angular/core';

@Component({
     ....
})

export class appComponent {

    private url: string = "http://localhost:9000";

    constructor() {
        (<any>window).SampleFunction = this.SampleFunction.bind(this);
    }


    SampleFunction() {
        console.log('SampleFunction');
    }

}

当我点击它时,它显示错误如:

enter image description here

1 个答案:

答案 0 :(得分:2)

是!我确实解决了使用angular-4和iframe发送或接收数据的问题。

示例:-

app.component.html

<iframe width="100%" frameBorder="0" [src]="url | safe" style="height: 500px; border: none;" (load)="onLoad()" #TheIframe></iframe>

app.component.ts

import { Component, HostListener, ViewChild } from '@angular/core';

export class AppComponent {
    @ViewChild('TheIframe') TheIframeEl: any;

    constructor() {
        (<any>window).reciveDataFromIframe = this.reciveDataFromIframe.bind(this);
    }

    onLoad() {
        const object = {
            'message': "Hello World!"
        };
        this.TheIframeEl.nativeElement.contentWindow.postMessage(object, 'http://localhost:3001');
    }

    @HostListener("window:message", ["$event"])
    reciveDataFromIframe(event: MessageEvent) {
        this.load(event.data);
    }

    load(data) {
        console.log('data', data);
    }
}

Reference send and receive data using iframe