Angular way to submit form data to iframe

2019-07-24 18:16发布

问题:

I have html like below

<form name="aForm" show="true" action="iframeUrl" target="iFrame" method="post">
  <input id="input_data" type="text" name="input_data" value="data" />
  <input id="input" type="submit" value="post">
</form>

<iframe id="iFrame" name="iFrame" src="iframeUrl" height="500" width="400" border=0>
  <p>Your browser does not support iframes.</p>
</iframe>

I already have the data I want to submit to the iframe when the page is loaded. What I want to do is have my angular controller submit the form to the targeted iframe as soon as the page is loaded. Clicking the submit type input I created gives me the result I'm looking for in the iFrame but I do not want the user to have to do that, or even for the form to be visible to the user. I've seen quite a few pure javascript solutions for this but they don't look like they really mesh with the angular way of doing things. Any suggestions of best practices and how to do this in angular? I'm new to the framework so explanations would be appreciated as well.

回答1:

I don't know if this is an ideal solution but I found something like this works.

window.iframeLoad = function(){
            if (! _this.submitted) {
                document.getElementById('aForm').submit();
            }
            _this.submitted = true;
        };

Then make the iframe

<iframe id="iFrame" name="iFrame" src="iframeUrl" height="500" width="400" border=0 onload="iframeLoad()">
  <p>Your browser does not support iframes.</p>
</iframe>

I'd still be interested in hearing other thoughts on this solution or better ones.



回答2:

This works for me in Angular 2

    <form target="frame" action="<Your URL to POST>" #form method="POST" hidden="hidden">
        <input name="token" value={{token}}>
    </form>

And call nativeElement.submit() from nginint() in your component.