Blog>
Snippets

Creating a Simple Angular Element

Demonstrate how to create a minimal Angular Element by turning a component into a custom element and bootstrapping it manually.
import { NgModule, Injector } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { createCustomElement } from '@angular/elements';
import { AppComponent } from './app.component';

// Define the module that declares the component
@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent],
    entryComponents: [AppComponent]
})
class AppModule {
    constructor(private injector: Injector) {}
    
    // Use the injector to create a custom element from the component
    ngDoBootstrap() {
        const el = createCustomElement(AppComponent, { injector: this.injector });
        customElements.define('my-custom-element', el);
    }
}
This code snippet includes the necessary imports and sets up an NgModule that declares the AppComponent. Within the AppModule class, the constructor injects the Injector service. The ngDoBootstrap method is used to create a custom element by passing the component and the injector to createCustomElement. It then defines the custom element with a tag name 'my-custom-element'.
import { Component } from '@angular/core';

// Define the component that will become a custom element
@Component({
    selector: 'app-root',
    template: '<p>Hello, Angular Element!</p>'
})
export class AppComponent {}
This code defines a simple Angular component with the selector 'app-root' and a template that renders a paragraph containing a greeting. This component will be turned into the custom element.
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

// Bootstrap the module as a custom element
platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .catch(err => console.error(err));
This code uses the platformBrowserDynamic function to bootstrap the AppModule. The bootstrap operation is invoked manually instead of using auto-bootstrap in the index.html. Any errors during bootstrapping are logged to the console.