Search code examples
javascriptangularjsangularpolymerweb-component

HTML import angular2 app and pass parameter


I want to use webcomponents and HTML import to import an angular2 module into another webapplication which do not use angular2. I know HTML import is only natively supported in few browsers but i will use the polymer framework to pollify other browsers.

I can import the angular app but i'm unable to pass parameters to the angular app from my web app that imports the angular app. I'm trying this:

<dom-module id="sale-stats">
  <link rel="import" href="../bower_components/polymer/polymer.html">
  <template>
    <!-- contains my angular app bundled js files -->
    <link rel="import" href="imports.html">
    {{saleid}} <!-- this displays the saleid just to see that the parameter is passed to the webcomponent -->

    <app-root saleid='{{saleid}}'>Loading... </app-root>
  </template>

  <script>
    HTMLImports.whenReady(function () {

      Polymer({
        is: 'sale-stats',

        properties: {
          saleid: {
                type: String,
                value: '0'
            }
        },
      });
    });
  </script>
</dom-module>

<script src="/Scripts/webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="http://localhost:9600/salestats/index.html" />
<sale-stats saleid="1234567"></sale-stats>

How do i pass parameters to my angular app when using the angular app as a webcomponent that is imported into another app? Or is it just completely wrong to try and import an angular app as an webcomponent?


Solution

  • In order to polyfill HTML Imports, you just have to include HTMLImports.js which is available in the webcomponents.js repository. You can install it with bower (or npm):

    bower install webcomponentsjs
    

    Just include the polyfill before the <link> element:

    <script src=".../bower_components/webcomponentsjs/HTMLImports.js"></script>
    

    To wait for the imported file to be loaded, you can use the Promise, or instead wait for the standard onload event. For example:

    <script src=".../bower_components/webcomponentsjs/HTMLImports.js"></script>
    <link rel="import" href="imports.html" onload="run( 1234567 )">
    

    Inside the imported HTML file:

    <!-- contains my angular app bundled js files -->
    <script>
        function run ( id ) 
        {
            var app = document.createElement( 'app-root' )
            app.setAttribute( 'saleid', id )
            document.body.appendChild( app )                
        }
    </script>
    

    Notes: you can also place the onload callback function in the main document. Also, the import is synchronous on native implementation (Chrome and Opera); use async in <link> if you don't want to block the parsing.