Using angular 4 component as widget (on a static w

2020-07-30 00:31发布

问题:

long time lurker, first time asking :)

Is there any way to inject my angular 4 component (widget-like mail window app using webpack) into any static website, preferably using the <script> tag?

Found some blog posts but all of them are using SystemJS and my app is using webpack and there seem to be no results with that.

Thanks for any help!


EDIT: Problem solved, thanks for all contributions :)

回答1:

Angular app must always have root element, which is usually inserted in index.html's <body>. Assuming you have written your widget, in which root component f.e. is <widget>, you can mix it up with any static markup you have on your page:

<!doctype html>
<html>

  <head>
    <title>title</title>
  </head>

  <body>

    <header>
        <nav>Brand</nav>
    </header>

    <aside>
        Menu
        <!-- It can also be injected in any other element -->
        <widget></widget>
    </aside>

    <main>
        Content
    </main>

  </body>

</html>

If your app is bootstrapped with Angular CLI, which under the hood uses webpack, just put your static markup in src/index.html and you are done.

Edited: if you want to inject your widget into any other page, you can try to do this with following steps:

  1. Create one more script, in which create your app's root element and then paste it into the body
  2. Bundle your Angular app into static files. Better to have one .js file for simplicity.
  3. Dynamically create script element and supply static bundle's path to script's src
  4. Dynamically inject it into the page's body

Kind of like that:

<script type="text/javascript" charset="utf-8">
    window.addEventListener('load', () => {
      const widgetElement = document.createElement('widget')
      // document.body is not necessary here, it can be any other element
      document.body.appendChild(widgetElement) 

      const widgetCode = document.createElement('script')
      widgetCode.src = '<path to bundled angular app>'
      document.body.appendChild(widgetCode)
    })
</script>

I've created plnkr, which may help you a bit



回答2:

you can use custom elements in angular to creat a custom component and then you build your projetc with npm run build element, it will generate a script .js for you where all your applications is built into. And then you can inject the script into any other project or a simple html page and it will load youre application. May be my explanation is not very clear you can see cutom elements in angular main website.