A2UI: Declarative Generative UI in Angular
Letting Spring AI agents render rich, interactive native Angular components inside chat streams safely—without raw HTML generation or duplicated templates.
A2UI in 30 Seconds
Asking an LLM to generate raw HTML or JSX inside a chat stream introduces XSS risks, visual drift, and dead non-interactive markup. A2UI (Agent-to-UI) solves this with declarative surface descriptions: the backend emits a component name and structured payload over AG-UI, and an Angular registry validates the data before dynamically mounting your existing native components with NgComponentOutlet and CSS Container Queries.
Introduction
Looking for the SSE transport, capability sync, and Signals action pipeline? Start with the AG-UI Guide. Looking for monorepo setup? See the Mise Guide.
A2UI (Agent-to-UI) is a declarative generative UI pattern where an AI agent sends a lightweight surface description—a surfaceId, a whitelisted component name, and structured JSON data—instead of raw HTML, Markdown tables, or generated JSX.
When an agentic assistant lives inside a rich web application, streaming plain text forces users to read walls of Markdown for data your application already knows how to display interactively. Conversely, letting an LLM emit raw HTML or dynamically evaluated templates opens security holes and breaks your design system.
A2UI bridges that gap by separating what to show (structured data emitted by the agent) from how to render it (native, pre-built components owned by the frontend).
Comparison: A2UI Declarative Surfaces vs. LLM-Generated HTML vs. Hardcoded Chat Templates
| Dimension | A2UI (Declarative Registry) | LLM-Generated HTML / JSX | Hardcoded Chat Templates |
|---|---|---|---|
| Security | Whitelisted native components only | High XSS & injection surface | Safe, but rigid |
| Template Reuse | Reuses existing domain components | Re-invents markup per prompt | Duplicates app cards inside chat |
| Interactivity | Full app state, routing, & stores | Static or fragile inline handlers | Requires manual wiring per card |
| Visual Consistency | Inherits theme, tokens, & WCAG AA a11y | Frequently drifts from design system | Drifts when main app cards evolve |
| Runtime Safety | Schema-validated input mapping | Unpredictable malformed markup | Coupled to ad-hoc string parsing |
How Can A2UI Help Me?
Pairing A2UI with AG-UI turns AI chat responses from passive text into first-class, interactive parts of your application:
1. Security by Whitelist
The LLM can never inject arbitrary <script> tags, inline styles, or unapproved DOM nodes. Only component names explicitly registered in the frontend's surface whitelist can ever be instantiated.
2. Zero Template Duplication
Your application already has polished, accessible domain components. A2UI mounts those exact components inside the conversation stream instead of forcing you to maintain parallel chat-only copies.
3. Design System and Accessibility Parity
Because mounted surfaces are real native components inside your application tree, they automatically inherit your active theme, light/dark color mode, keyboard navigation, and WCAG AA accessibility compliance.
4. Schema-Validated Runtime Safety
Every incoming surface payload is validated against a typed schema before reaching component inputs. If a model or upstream tool produces an unexpected field shape, the host falls back gracefully instead of throwing runtime template errors.
Transporting A2UI over AG-UI
A2UI does not require a separate WebSocket or custom HTTP endpoint. It travels inside the same Server-Sent Events (SSE) stream described in the AG-UI Protocol section, carried by AG-UI's ACTIVITY_SNAPSHOT event with activityType: "a2ui-surface".
The Surface Wire Contract
Keep the payload intentionally minimal—just enough to identify the surface instance, select a registered component, and pass structured domain data:
data: {"type":"ACTIVITY_SNAPSHOT","messageId":"a2ui-8f3c","activityType":"a2ui-surface","content":{"surfaceId":"a2ui-8f3c","component":"FlightCard","data":{"callsign":"KLM1298","origin":"EHAM","destination":"EGLL","status":"EN_ROUTE"}}}
Each surface payload has three core fields:
surfaceId— unique identifier for the rendered surface instance (also enables in-place updates if the agent emits a newer snapshot for the same surface)component— symbolic name resolved against the frontend's component whitelistdata— structured JSON payload validated and mapped to the component's inputs
Deep Dive: End-to-End A2UI Surface Rendering Pipeline
Here is how a declarative surface flows from an agent backend to a live native component inside the chat timeline:
Implementing A2UI in Spring Traffic Control
In Spring Traffic Control, A2UI connects Spring Boot + Spring AI on the backend with Angular Signals on the frontend so the agent can render the exact same FlightCard, StationCard, and NearestAirportsCard components used across the rest of the application.
Emitting Surfaces From Spring AI @Tool Methods
Using the thread-safe turn emitter introduced in the AG-UI Spring Boot Agent guide, any @Tool can emit an ACTIVITY_SNAPSHOT surface as a side-channel event while returning a short, token-efficient confirmation string to the LLM:
// Pseudocode: emitting an A2UI surface from the per-turn emitter
class TurnEmitter(private val publish: (Event) -> Unit) {
fun emitSurface(component: String, data: Map<String, Any?>): String {
val surfaceId = "a2ui-${UUID.randomUUID()}"
val payload = mapOf("surfaceId" to surfaceId, "component" to component, "data" to data)
publish(ActivitySnapshotEvent(surfaceId, "a2ui-surface", payload))
return surfaceId
}
}
// Pseudocode: dual-channel @Tool method
@Tool(description = "Look up a scheduled flight by callsign and display its FlightCard.")
fun findFlightByCallsign(callsign: String): String {
val flight = flightService.findByCallsign(callsign)
?: return "No flight found for callsign '$callsign'."
emitter.emitSurface("FlightCard", flight.toSurfaceMap())
return "Displayed FlightCard for ${flight.callsign} (${flight.origin} -> ${flight.destination})."
}
The Angular Surface Registry & Capability Sync
Rather than scattering @switch (surface.component) blocks across chat templates, centralize every allowed component in a typed Surface Registry. Each entry pairs a component class with an input mapper backed by a runtime schema library (such as Zod) that validates unknown wire data and returns clean input() bindings (or null on failure):
// Pseudocode: centralized A2UI surface registry
interface SurfaceRegistryEntry {
readonly component: Type<unknown>;
readonly mapInputs: (data: unknown) => Record<string, unknown> | null;
}
const SURFACE_REGISTRY: Record<string, SurfaceRegistryEntry> = {
StationCard: {
component: StationCardComponent,
mapInputs: (data) => parseWithSchema(StationSchema, data, (station) => ({ station, compact: true })),
},
FlightCard: {
component: FlightCardComponent,
mapInputs: (data) => parseWithSchema(FlightSchema, data, (flight) => ({ flight })),
},
NearestAirportsCard: {
component: NearestAirportsCardComponent,
mapInputs: (data) => parseWithSchema(NearestAirportsSchema, data, (result) => ({ result })),
},
};
Using a schema library like Zod as the single source of truth also lets you export standard JSON Schema descriptors for each surface and sync them alongside frontend actions on app boot via POST /api/agui/sync (covered in the AG-UI Capability Sync section). Whenever you add or update a card, the renderer, runtime validation, and backend prompt stay in lockstep automatically.
Dynamic Mounting With NgComponentOutlet
With the registry in place, rendering any A2UI surface inside a chat message takes a single, lightweight host component powered by Angular Signals and NgComponentOutlet.
Host Component
// Pseudocode: signal-driven A2UI surface host
@Component({
selector: "app-a2ui-surface-host",
imports: [NgComponentOutlet],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { class: "block w-full" },
})
export class A2UiSurfaceHostComponent {
readonly surface = input.required<A2UiSurface>();
protected readonly resolved = computed(() => {
const { component, data } = this.surface();
const entry = SURFACE_REGISTRY[component];
if (!entry) return null;
const inputs = entry.mapInputs(data);
return inputs ? { component: entry.component, inputs } : null;
});
}
Host Template
@if (resolved(); as match) {
<ng-container
[ngComponentOutlet]="match.component"
[ngComponentOutletInputs]="match.inputs"
/>
} @else {
<div role="status" class="surface-fallback">
Unable to render surface "{{ surface().component }}".
</div>
}
Why this works so cleanly:
- Signal-driven resolution:
computed()only re-runs when thesurface()input changes, keepingOnPushchange detection minimal even during fast token streaming. - Zero unsafe casts:
NgComponentOutletbinds[ngComponentOutletInputs]directly to the target component'sinput()signals. - Graceful degradation: Unknown component names (for example, during a rolling backend deployment) or malformed payloads render a clean, accessible fallback without crashing the chat drawer.
Responsive Surfaces With Container Queries
Reusing a component across your main application and an AI chat drawer exposes a classic CSS limitation: viewport @media queries measure the browser window, not the chat panel.
On a 1440px desktop monitor, a FlightCardComponent rendered inside a 400px-wide chat drawer still matches @media (min-width: 1024px). A horizontal multi-column desktop card layout suddenly overflows or squishes awkwardly inside the narrow drawer.
The Drop-In Recipe: :host Container Context + @container
Instead of adding fragile isInChat boolean inputs to every reusable card, make the component's host element a CSS containment context and style its internal layout with @container queries:
/* flight-card.component.css */
:host {
display: block;
container-type: inline-size;
container-name: flight-card;
}
/* Mobile-first & narrow chat drawer base layout (< 480px) */
.flight-card-grid {
display: grid;
grid-template-columns: 1fr;
gap: 0.75rem;
}
.flight-route-meta {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
/* Expands automatically when placed in a wide dashboard or detail page */
@container flight-card (min-width: 480px) {
.flight-card-grid {
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 1.25rem;
}
.flight-route-meta {
flex-direction: row;
justify-content: space-between;
}
}
With this single pattern:
- Inside a 400px chat drawer,
FlightCardComponentstacks cleanly into a vertical mobile layout. - Inside a 1400px dashboard, the exact same component expands horizontally into a spacious multi-column row.
- If the user resizes the chat panel or switches to a
320pxmobile screen, the card adapts automatically with zero JavaScript resize observers.
Gotchas, Practical Pitfalls & Troubleshooting
Losing context on card-only assistant turns
When a @Tool emits an A2UI card and the model replies with little or no prose, filtering conversation history by m.text.trim().length > 0 drops the turn completely. As noted in the AG-UI Signals guide, serialize a compact summary like [Displayed UI: StationCard(icao=EHAM, iata=AMS)] into initialMessages so follow-up prompts ("open that station's page") still resolve accurately.
container-type: inline-size collapsing intrinsic width
Setting container-type: inline-size on :host disables intrinsic inline sizing for that element. Always pair it with display: block (and ensure the parent container—such as A2UiSurfaceHostComponent—has width: 100%) so the card does not collapse to 0px inside flex containers.
NgComponentOutlet and component output() events
[ngComponentOutletInputs] binds signal input() properties seamlessly, but it does not subscribe to output() emitters in the template. You have two clean options: keep your domain cards pure/presentational with output() emitters and subscribe to them in the host via viewChild(NgComponentOutlet)?.componentInstance inside an effect((onCleanup) => ...) (forwarding interactions to your action control service), or wire card actions directly to injectable Angular services so cards stay self-contained wherever they are mounted.
Strict schema validation vs. partial backend fields
Real-world telemetry (such as live ADS-B flight states) often contains null values where TypeScript expects undefined. Treat non-critical metadata fields as nullable/optional in your surface schemas so a missing altitude or squawk code does not reject the entire card.
Summary
Together, AG-UI and A2UI give you a complete, production-ready architecture for agentic web applications:
- AG-UI handles the real-time SSE transport, versioned capability sync, contextual UI snapshots, and reactive app commands.
- A2UI rides over AG-UI's
ACTIVITY_SNAPSHOTevents to render whitelisted, schema-validated native components viaNgComponentOutlet. - CSS Container Queries let a single component adapt seamlessly between full-width dashboards and narrow chat drawers—delivering secure, accessible, zero-duplication generative UI.