

Open the index.html file and add the following code that will be used to test if our web component works properly: Building our Web ComponentĪfter compiling our project and getting a bunch of JavaScript files, let’s see how we can use our web component outside of Angular.Ĭreate an index.html file inside some folder and copy the mentioned JavaScript files from the dist folder of the Angular project in the same folder. That’s it! This is all the required code to build a custom element from our Angular component.

For example, open the tsconfig.json file and change the target to es2015: ) Ĭfine('news-widget', el) $ ng add command will take care of installing the package ( v7.2.15 as of this writing) and updating the necessary files automatically.Īt this time, Angular Elements has a bug that causes an Uncaught TypeError with the message: Failed to construct 'HTMLElement': Please use the 'new' operator, this DOM object constructor cannot be called as a function. Head back to your terminal, navigate to your project’s folder and invoke the ng add command as follows: $ cd angular-web-component You can set up Angular Elements in your Angular project very easily using the ng add command. You can easily create a custom element and the package will take care of converting the required Angular functionality to the corresponding native HTML APIs. The package exports a ()``() API that provides a bridge from Angular's component interface and change detection functionality to the built-in DOM API.Īngular Elements allows you to transform an Angular component to a custom element (web component). Slim.js: An open source lightweight web component library that provides modern features like data binding.Polymer: This project by google provides a set of tools for creating custom elements.It’s created and maintained by the Ionic team and it was used to create the Ionic UI components. It allows to use simply to use TypeScript API to build components just like you would use a modern framework such as Angular or React. Stencil: An open source web components compiler that generates standards-compliant web components.

You can either use the browser builtin JavaScript APIs to create custom elements or use existing libraries that abstracts away all the complexities involved in creating web components with vanilla JavaScript. For example if AppMenu is the name of our custom element, we can use it as follows in our HTML document: You can then use the custom element just like you would normally use any HTML tag. You can create a custom web component using JavaScript and a set of builtin methods such as fine().
