Search code examples
javascriptangulartypescriptweb-component

Angular 6 create web component


I have the following problem. I have an application constructed using Angular 6. I want to create a web component that will contain this application and be able to use it as part on a different web application. I have followed this tutorial and I have modify it based on my needs: https://codingthesmartway.com/angular-elements-a-practical-introduction-to-web-components-with-angular-6/

The result is that nothing renders on the screen and now error exist in the browser. On the browser source files I can confirm that the js file that contains my web component is loaded successfully.

Here is what I have:

In app.module.ts

@NgModule({


declarations: [
    AppComponent
  ],
  imports: [
   //different modules here
  ],
  providers: [
    //different services here
  ],
  entryComponents: [AppComponent]
})

export class AppModule { 
  constructor(private injector: Injector) {
    const myApp = createCustomElement(AppComponent, { injector });
    customElements.define('app-component', myApp);
  }
  ngDoBootstrap(){ }
}

In package.json

  [...]
"scripts": {
    [..]
    "build:elements": "ng build --prod --output-hashing none && node app-element.js"
}

In app-element.js

 const fs = require('fs-extra');
const concat = require('concat');

(async function build() {
    const files = [
        '../../target/app/runtime.js',
        '../../target/app/polyfills.js',
        '../../target/app/scripts.js',
        '../../target/app/main.js'
    ]

    await fs.ensureDir('app-element')

    await concat(files, 'elements/app-component.js');

    await fs.copyFile('../../target/app/styles.css', 'elements/styles.css');

    await fs.copy('../../target/app/assets/', 'elements/assets/');

})()   

After I build the element by running the following command 'npm run build:elements'. I copy the files into a different application and import the appropriate links into the index.html.

Here is my index.html

<!DOCTYPE html>
<html lang="en">

<head>
   <script type="text/javascript" src="./app-component.js"></script>
</head>
<body>
    <app-component></app-component>
</body>
</html>

Any suggestions on this problem?

Thanks in advance


Solution

  • Problem solved. It was a routing problem