Reputation: 11184
I am using to display the iframe in angular4 application i.e in localhost:4201. iframe page is from localhost:9000. In my iframe page there is one button. if i click the button, need to execute my angular4 component function. I tried this one, but it throws error
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>
localhost: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');
}
}
when i click this, its shows error like:
Upvotes: 1
Views: 2863
Reputation: 11184
Yes!. I did solve the problem send or receive data using angular-4 and iframe.
example :-
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
Upvotes: 4