I have one app built with Angular 5.2. I've also built a web component from Angular 8.0. If I'm about to put that web component in a static html I would do it like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom Button Test Page</title>
<!-- This is the Web Component import -->
<script src="elements.js"></script>
</head>
<body>
<custom-button></custom-button>
</body>
</html>
Running this index.html file would have the web component built in. How ever if I apply the same approach to an Angular app (to include it in my Angular 5.2 app), it doesn't work.
If I try importing straight from main index.html, I get the file not found error. If I import it from angular.json scripts, I will get unexpected token error.
How exactly am I supposed to import an Angular web component into existing Angular app?
Create a new Angular project: **Enable the use of Web Components**, by adding a schemas property inside the @NgModule config in app. module. ts , and pass it an array with the CUSTOM_ELEMENTS_SCHEMA constant. This allows Angular to understand the HTML Web Component selector, because it's a non-Angular component.
Web Components are the concept of components from frameworks like React or Angular, but built for the web overall, framework-agnostic. What does that mean? We are used to our simple HTML tags in our UI. For example, we know tags like div , span , and others.
To get started, go ahead and install bit-cli, then head over to the project from which to share the components, and initialize a bit workspace. Then, head over to bit. dev and create a free account. Then, create a collection to host your shared components.
The solution was to import the script in angular.json / .angular-cli.json
"scripts": [
"assets/elements.js"
]
How ever if you leave it like that, you will still get the errors most likely to multiple zone.js imports - One coming from your Angular App and other one from your Angular Web Components app. The solution is to disable one of those. Logically it would be to disable the one coming from a web component - but it turned out that it doesn't work. You will have to remove the import of zone.js from your main Angular App, and keep it in your web component.
Go to polyfills.ts and comment out or remove
import 'zone.js/dist/zone';
Also don't forget to add CUSTOM_ELEMENTS_SCHEMA to your AppModule so that Angular knows you will be using outside components.
@NgModule({
declarations: [ ... ],
bootstrap: [ ... ],
imports: [ ... ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ]
})
Now you can use your web component anywhere in your application with
<custom-button></custom-button>
WARNING: This approach will not work if you are running different versions of webpack in those two applications
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With