Blog>
Snippets

Dynamic Loading of Angular Elements

Provide an example of how to load and initialize Angular Elements dynamically in a vanilla JavaScript application, using a combination of custom elements definitions and runtime data fetching.
// 1. Dynamically load the script for Angular elements
const script = document.createElement('script');
script.src = 'path_to_your_angular_elements_bundle.js';
script.onload = () => {
    // This function will be called once the script is loaded

    // 2. Define your Angular elements (this part is usually done in the Angular project)
    // customElements.define('my-custom-element', MyCustomElement);

    // 3. Create a new instance of the element
    const element = document.createElement('my-custom-element');

    // 4. Append the new element to the DOM
    document.body.appendChild(element);

    // 5. Optionally pass data to your element or handle events
    element.addEventListener('someEvent', (event) => {
        console.log('Event from my-custom-element:', event.detail);
    });
};
document.head.appendChild(script);
This code snippet dynamically loads a JavaScript file which contains the Angular elements bundle. After the script is loaded, it defines the custom elements, creates an instance of the custom element and adds it to the DOM. It also adds an event listener to the newly created element that logs events triggered by the custom element.