Blog>
Snippets

Using Angular Elements in a Non-Angular Application

Illustrate the integration of Angular Elements into a non-Angular application, emphasizing how to handle bootstrapping and lifecycle hooks.
customElements.define('my-angular-element', MyAngularElement);
Register the custom element 'my-angular-element' which is the Angular component wrapped as an Angular Element. Replace 'MyAngularElement' with the class that Angular provides from the Angular Element wrapping process.
// Include the necessary polyfills for Angular Elements
if (!window.customElements) {
  document.write('<!-- Polyfills for Angular Elements -->\n<script src="https://unpkg.com/@webcomponents/webcomponentsjs@2/webcomponents-bundle.js"></script>');
}
This checks for the Custom Elements API support and includes the necessary polyfills if it's not supported by the browser. Polyfills are hosted on a CDN for simplicity.
function onElementReady() {
  // This function could be used to initialize or configure the element
  const element = document.createElement('my-angular-element');
  document.body.appendChild(element);
}
Define a function that creates an instance of the Angular Element when needed. This function could also be used to pass in attributes or properties to the Element before it's attached to the DOM.
document.addEventListener('DOMContentLoaded', function() {
  // Ensure the Angular Elements are defined before using them
  if (window.customElements.get('my-angular-element')) {
    onElementReady();
  } else {
    window.customElements.whenDefined('my-angular-element').then(onElementReady);
  }
});
This code waits for the DOM content to be fully loaded, and checks if the 'my-angular-element' is already defined. If not, it waits for the custom element to be defined using the whenDefined promise and then calls the function to create and append the Angular Element to the DOM.