Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 74 ยท Tooling and Ecosystem

Angular Elements and Web Components

Package an Angular component as a standard custom element with @angular/elements, use it in plain HTML, and learn how inputs, outputs and the limits map to the Web Components standard.

Sometimes you need an Angular component to live outside an Angular app: in a CMS page, in a React or plain HTML site, or in a micro-frontend shell owned by another team. Angular Elements solves this by wrapping a component as a custom element, a browser-native tag such as <user-card name="Ada"> that works anywhere HTML works.

This lesson explains the Web Components standard in a few minutes, shows how createCustomElement() maps component inputs and outputs onto it, and is honest about the costs. You should know Inputs and Outputs and the basics of Services and Dependency Injection.

Real versus stand-in. The typescript, bash and Angular html blocks are real code to read; the site cannot build Angular, so the Angular Elements package itself never runs here. The runnable examples show the browser standard that it builds on (a hand-written custom element you can try in this page) and a TypeScript stand-in for the naming and coercion rules.

What a custom element is

The browser lets you register your own tag name with customElements.define(). The name must contain a hyphen so it can never clash with a built-in tag. The class you register can react to being added to the page (connectedCallback), being removed (disconnectedCallback), and to changes of attributes you list in observedAttributes (attributeChangedCallback). Events travel outward as CustomEvents. That is all the standard asks of a component, and any page can use it without a framework.

A hand-written custom element (the standard behind Angular Elements)

The tag is used like any HTML element, attributes flow in, and a DOM event flows out. A page built with React, Vue or no framework at all could do exactly the same thing with it.

Packaging an Angular component

@angular/elements does that wiring for you. It reads the component's inputs and outputs, creates a class like XCounter, and starts a small Angular application for each element instance so that change detection, templates and dependency injection work inside.

Terminal
ng add @angular/elements
TypeScript
// counter.ts
import { Component, input, output, signal } from '@angular/core';

@Component({
  selector: 'app-counter',
  template: `
    <span>{{ label() }}: {{ count() }}</span>
    <button type="button" (click)="increment()">+1</button>
  `,
})
export class Counter {
  label = input('Count');
  start = input(0);
  countChange = output<number>();

  protected readonly count = signal(0);

  protected increment(): void {
    this.count.update((n) => n + 1);
    this.countChange.emit(this.count());
  }
}
TypeScript
// main.ts: no root component, we only define elements
import { createApplication } from '@angular/platform-browser';
import { createCustomElement } from '@angular/elements';
import { Counter } from './counter';

(async () => {
  const app = await createApplication({ providers: [] });
  const element = createCustomElement(Counter, { injector: app.injector });
  customElements.define('ng-counter', element);
})();

createApplication() builds an Angular application without a root component to mount, which is what you want when the page, not Angular, decides where elements go. createCustomElement takes the component and the injector the elements will share, and returns a class for customElements.define.

After ng build, the output files (main.js, polyfills.js if any, and styles) can be copied to any site and loaded with plain <script> tags:

HTML
<script src="main.js" type="module"></script>

<ng-counter label="Visits" start="3"></ng-counter>

<script>
  document.querySelector('ng-counter')
    .addEventListener('countChange', (e) => console.log(e.detail));
</script>

How inputs and outputs map

Angular In the browser
input() named label the DOM property label and the attribute label
input() named userName the property userName and the dash-case attribute user-name
output() named countChange a CustomEvent named countChange; the emitted value is event.detail
@Output() closed (older style) a CustomEvent named closed

Two details cause most surprises. First, attributes are always strings: start="3" arrives as "3", so use a transform such as numberAttribute on the input if you need a number (Inputs and Outputs). Setting the property from JavaScript (el.start = 3) can pass real objects and arrays, so use properties for non-string data. Second, event names are used exactly as written; the dash-case conversion applies only to attributes.

TypeScript A stand-in for the naming and coercion rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The numbers and booleans become real values only because the stand-in has transforms; in a real Angular component those would be numberAttribute and booleanAttribute on your inputs.

Limits and when to use it

Angular Elements is a bridge, not a free lunch:

  • Size. Each bundle contains Angular's runtime. A small widget that costs 60 KB in a framework-free design costs far more here. If several elements share one build, they share the runtime too, so publish them as one bundle.
  • Content projection. <ng-content> works at creation time, but it is not the same as native <slot> elements. Complex projection is a common source of bugs (Content Projection).
  • Styles. With the default encapsulation, Angular's component styles are added to the host page's <head>. For a widget that must not collide with the host's CSS, use ViewEncapsulation.ShadowDom (Styling and Encapsulation).
  • Services. Elements that share an injector share its services, which is handy for a small shared store and surprising if you expected isolation.
  • SSR and SEO. Custom elements render in the browser, so search engines and users without JavaScript see only the empty tag.
  • Versions. Two elements built with different Angular versions on one page both bring their own runtime. It works, but it is heavy.

Use it for dropping an Angular widget into a non-Angular page, for gradual migrations and for micro-frontends. For a normal Angular application, ordinary components are simpler and smaller.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a custom element name have to contain?

    The standard requires a hyphen so custom names can never collide with present or future built-in HTML tags.
  2. 2. How does an Angular output reach the host page of a custom element?

    Angular Elements dispatches a DOM CustomEvent named after the output and puts the emitted value in detail.
  3. 3. Why does <ng-counter start="3"> give your input the string "3" unless you add a transform?

    Attributes are text. A transform such as numberAttribute converts them, or you can set the property from JavaScript with a real number.
  4. 4. Which is a real cost of Angular Elements?

    Elements are normal Angular code, so the runtime ships with them. That is fine for substantial widgets and wasteful for tiny ones.

Summary

  • A custom element is a browser-native tag registered with customElements.define(); attributes go in and CustomEvents come out.
  • createCustomElement(Component, { injector }) wraps an Angular component, and createApplication() creates the app without a root component.
  • Inputs become properties and dash-case attributes (strings only); outputs become CustomEvents with the value in detail.
  • Use it for non-Angular hosts and micro-frontends, and watch for bundle size, projection and style collisions.

Next: see how to ship the code from your app in Build and Deploy.