How to use a web component(created in Angular 17) in HTML external project

303 Views Asked by At

The goal is to create a web components using angular and use it in an external html file.

I created the web component : 'my-web-component'

(async () => {
  const app: ApplicationRef = await createApplication(appConfig);

  // Define Web Components
  const MyComponent = createCustomElement(MyComponentComponent, { injector: app.injector });
  customElements.define('my-web-component', MyComponent);
})();

I served(ng serve) and the Custom element works! So, I build my project getting 3 files : main.js, polyfills.js and index.html (/dist). I tested the dist/index.html with Live Server and the Custom element still works.

<!doctype html>
<html lang="en" data-critters-container>
<head>
  <meta charset="utf-8">
  <title>WebComponentClean</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles-5INURTSO.css"></head>
<body>
  <my-web-component></my-web-component>
  <script src="polyfills-RT5I6R6G.js" type="module"></script>
  <script src="main-QVCUGX7F.js" type="module"></script>
  <script src="prova.js"></script>
</body>
</html>

enter image description here

Now there is the problem I created a second index2.html in this project, but out of src folder, and I tested my web component:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/dist/web-component-clean/browser/styles-5INURTSO.css">
</head>
<body>
    <my-web-component></my-web-component>
    <script src="/dist/web-component-clean/browser/main-QVCUGX7F.js" type="module"></script>
    <script src="/dist/web-component-clean/browser/polyfills-RT5I6R6G.js" type="module"></script>
    <script src="/dist/web-component-clean/browser/prova.js"></script>
</body>
</html>

errore della console

file main.js

1

There are 1 best solutions below

0
Naren Murali On BEST ANSWER

There is a big difference between the order of imports, if you look at the second index.html, main and polyfills are swapped! reverse it!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/dist/web-component-clean/browser/styles-5INURTSO.css">
</head>
<body>
    <my-web-component></my-web-component>
    <script src="/dist/web-component-clean/browser/polyfills-RT5I6R6G.js" type="module"></script>
    <script src="/dist/web-component-clean/browser/main-QVCUGX7F.js" type="module"></script>
    <script src="/dist/web-component-clean/browser/prova.js"></script>
</body>
</html>