Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

angular.md

348 lines10.4 KB

1---
2title: Angular Chat UI
3id: typed-headless-ui-angular
4order: 8
5description: "Render a streaming chat in Angular with your own standalone components. createChatHook types every tool, part, and interrupt, and chat state is signals."
6keywords:
7 - tanstack ai
8 - createChatHook
9 - angular
10 - injectAppChat
11 - headless ui
12 - ToolProps
13---
14​
15`createChatHook` from `@tanstack/ai-angular/ui` binds your chat options and components once. Tool calls and approvals stay typed.
16​
17Each screen then creates a chat with `injectAppChat()` and renders it with `<ai-chat [chat]="chat" />`.
18​
19- Widgets are standalone Angular components with signal inputs.
20- Chat state is signals.
21- The layout renders its slots with `NgComponentOutlet`.
22​
23You supply every visible component. There is no default markup or style.
24​
25## Quick setup
26​
271. Install the packages:
28​
29<!-- ::start:tabs variant="package-manager" mode="install" -->
30​
31angular: @tanstack/ai @tanstack/ai-angular @tanstack/ai-openai
32​
33<!-- ::end:tabs -->
34​
352. Put `OPENAI_API_KEY` in your server environment. Then add a `POST` route at `/api/chat`:
36​
37```ts
38import {
39 chat,
40 chatParamsFromRequest,
41 toServerSentEventsResponse,
42} from '@tanstack/ai'
43import { openaiText } from '@tanstack/ai-openai'
44​
45export async function POST(request: Request) {
46 const { messages, threadId, runId } = await chatParamsFromRequest(request)
47​
48 const stream = chat({
49 adapter: openaiText('gpt-6.1-sol'),
50 messages,
51 threadId,
52 runId,
53 })
54​
55 return toServerSentEventsResponse(stream)
57```
58​
593. Create `src/app/chat.ts`:
60​
61```ts
62import { Component, input } from '@angular/core'
63import type { Type } from '@angular/core'
64import { NgComponentOutlet } from '@angular/common'
65import { fetchServerSentEvents } from '@tanstack/ai-angular'
66import {
67 createChatHook,
68 type MessageProps,
69 type PartProps,
70} from '@tanstack/ai-angular/ui'
71​
72const chatOptions = {
73 connection: fetchServerSentEvents('/api/chat'),
75​
76@Component({
77 selector: 'app-chat-layout',
78 imports: [NgComponentOutlet],
79 template: `
80 <section>
81 <ng-container [ngComponentOutlet]="Messages()" />
82 </section>
83 `,
84})
85class ChatLayout {
86 Messages = input.required<Type<unknown>>()
87 Interrupts = input.required<Type<unknown>>()
88 Queue = input.required<Type<unknown>>()
89 Input = input<Type<unknown>>()
91​
92@Component({
93 selector: 'app-chat-message',
94 imports: [NgComponentOutlet],
95 template: `
96 <article [attr.data-role]="message().role">
97 <ng-container
98 [ngComponentOutlet]="Parts()"
99 [ngComponentOutletInputs]="{ message: message() }"
100 />
101 </article>
102 `,
103})
104class ChatMessage {
105 message = input.required<MessageProps<typeof chatOptions>['message']>()
106 Parts = input.required<Type<unknown>>()
108​
109@Component({
110 selector: 'app-text-part',
111 template: `<p>{{ part().content }}</p>`,
112})
113class TextPartView {
114 part = input.required<PartProps<typeof chatOptions, 'text'>['part']>()
116​
117@Component({
118 selector: 'app-empty-part',
119 template: ``,
120})
121class EmptyPart {
122 part = input<unknown>()
124​
125const { injectAppChat, Chat } = createChatHook({
126 options: chatOptions,
127 components: { layout: ChatLayout, message: ChatMessage },
128 partsComponents: { text: TextPartView, fallback: EmptyPart },
129})
130​
131@Component({
132 selector: 'app-chat',
133 imports: [Chat],
134 template: `
135 <main>
136 <ai-chat [chat]="chat" />
137 <form (submit)="send($event, field)">
138 <input #field name="message" />
139 <button type="submit">Send</button>
140 </form>
141 </main>
142 `,
143})
144export class ChatScreen {
145 chat = injectAppChat({ threadId: 'support-chat' })
146​
147 send(event: Event, field: HTMLInputElement) {
148 event.preventDefault()
149 const text = field.value.trim()
150 if (!text) return
151 field.value = ''
152 void this.chat.sendMessage(text)
153 }
155```
156​
1574. Render `<app-chat />` and send a message.
158​
159The reply streams into the page as the model writes it.
160​
161## How it works
162​
163- `createChatHook` runs once, at module scope. It binds `chatOptions` to your components. It returns `injectAppChat` and the `Chat` component (`<ai-chat>`).
164- `injectAppChat({ threadId })` creates one chat instance. Call it in a field initializer or a constructor.
165- The layout gets `Messages`, `Interrupts`, `Queue`, and `Input` as component inputs. `message` gets one message plus `Parts`.
166- `partsComponents.text` renders text. `fallback` catches every part type that you did not register.
167​
168Declare every input that the factory passes to a widget, even when the template does not use it.
169​
170## Next steps
171​
172Each step adds one thing to the quick setup. The [chat UI recipes](./recipes/index) have the full file for each one. The recipes use React. In Angular, each widget is a component class with `input()`.
173​
174### Render a tool
175​
176Add the tool to `tools` in `chatOptions`. Then register a component under the tool name in `toolsComponents`. A tool component gets the `part`, `result`, and `interrupt` inputs:
177​
178```ts ignore
179@Component({
180 selector: 'app-weather-tool',
181 template: `
182 @if (part().state === 'complete') {
183 <p>{{ part().input?.city }}: {{ part().output?.temperature }}</p>
184 } @else {
185 <p>Looking up weather</p>
186 }
187 `,
188})
189class WeatherTool {
190 part = input.required<ToolProps<typeof chatOptions, 'getWeather'>['part']>()
191 result = input<unknown>()
192 interrupt = input<unknown>()
194​
195// In createChatHook:
196toolsComponents: { getWeather: WeatherTool },
197```
198​
199The factory needs one entry for every tool in `chatOptions`. Full example: [Make a tool look right](./recipes/format-a-tool).
200​
201### Ask before a tool runs
202​
203Set `needsApproval: true` on the tool. The tool component then gets an `interrupt` input:
204​
205```ts ignore
206type DeleteFileProps = ToolProps<typeof chatOptions, 'deleteFile'>
207​
208@Component({
209 selector: 'app-delete-file-tool',
210 template: `
211 @if (interrupt()?.status === 'pending') {
212 <button (click)="interrupt()?.resolveInterrupt(true)">
213 Delete {{ part().input?.path }}
214 </button>
215 } @else {
216 <p>{{ part().input?.path }}</p>
217 }
218 `,
219})
220class DeleteFileTool {
221 part = input.required<DeleteFileProps['part']>()
222 result = input<DeleteFileProps['result']>()
223 interrupt = input<DeleteFileProps['interrupt']>()
225```
226​
227`resolveInterrupt(true)` approves. `resolveInterrupt(false)` denies. Full example: [Ask before a tool runs](./recipes/tool-approval).
228​
229### Ask the user your own question
230​
231Define the question with `defineInterrupt`. Add it to `interrupts` in `chatOptions`. Register a component under its id in `interruptsComponents.generic`, and render `Interrupts` in the layout:
232​
233```ts ignore
234const choosePlan = defineInterrupt({
235 id: 'choosePlan',
236 payloadSchema: z.object({ title: z.string() }),
237 responseSchema: z.string(),
238})
239​
240@Component({
241 selector: 'app-choose-plan',
242 template: `
243 <button (click)="interrupt().resolveInterrupt('pro')">
244 {{ interrupt().payload?.title }}
245 </button>
246 `,
247})
248class ChoosePlan {
249 interrupt =
250 input.required<InterruptProps<typeof chatOptions, 'choosePlan'>['interrupt']>()
252​
253// In createChatHook:
254interruptsComponents: { generic: { choosePlan: ChoosePlan } },
255```
256​
257The factory needs one entry for every interrupt id in `chatOptions`. Full example: [Ask the user your own question](./recipes/custom-interrupt).
258​
259### Read chat state inside a widget
260​
261Mapped components do not get `chat` as an input. Call `injectChatContext()` in a field initializer of the widget. This also moves the composer into the layout: register it as `input`, then render `Input` in the layout.
262​
263Create the contexts first with `createChatHookContexts()`, and pass them under `context`:
264​
265```ts ignore
266import { createChatHookContexts } from '@tanstack/ai-angular/ui'
267​
268const contexts = createChatHookContexts()
269​
270@Component({
271 selector: 'app-chat-input',
272 template: `
273 <form (submit)="send($event, field)">
274 <input #field name="message" [disabled]="chat.isLoading()" />
275 <button type="submit">Send</button>
276 </form>
277 `,
278})
279class ChatInput {
280 chat = contexts.injectChatContext()
281​
282 send(event: Event, field: HTMLInputElement) {
283 event.preventDefault()
284 const text = field.value.trim()
285 if (!text) return
286 field.value = ''
287 void this.chat.sendMessage(text)
288 }
290​
291// In createChatHook:
292context: {
293 chatRef: contexts.chatRef,
294 part: contexts.part,
295 interrupt: contexts.interrupt,
296},
297components: { input: ChatInput, layout: ChatLayout, message: ChatMessage },
298```
299​
300In the layout template, render the input with `<ng-container [ngComponentOutlet]="Input()" />`. Then remove the form from `ChatScreen`.
301​
302Chat state is signals. Read it by calling it, such as `chat.messages()`.
303​
304### Render markdown
305​
306`@tanstack/ai-angular/ui` has no `TextPart` component. Render `part().content` in your own text part, with the markdown library of your choice.
307​
308### Type a widget in its own file
309​
310Type each signal input from the prop types: `ToolProps`, `PartProps`, `InterruptProps`, and `MessageProps`. Pass `typeof chatOptions` and a name, then index the prop that you need:
311​
312```ts ignore
313part = input.required<ToolProps<typeof chatOptions, 'getWeather'>['part']>()
314```
315​
316Put `chatOptions` in a shared module so every widget file can import its type.
317​
318You now have a typed chat UI in Angular. Each widget is your own component.
319​
320## Advanced
321​
322### Slots and props
323​
324The config keys, part keys, and prop types are the same as in React. See [Every widget slot](./react#every-widget-slot).
325​
326The factory passes these inputs to the chrome:
327​
328- `layout`: `Messages`, `Interrupts`, `Queue`, and `Input`. If you render `Input` with no registered `input`, it renders nothing and warns once in development.
329- `message`: `message` and `Parts`. Pass `{ message: message() }` to `Parts`.
330​
331It passes these inputs to each widget:
332​
333- A part: `part`.
334- A tool: `part`, `result`, and `interrupt`.
335- An interrupt: `interrupt`.
336- A queue item: `item`.
337​
338`injectAppChat()` takes per-instance options: `threadId` (required), `initialMessages`, `live`, and `forwardedProps`. The factory also returns `ChatProvider` and `injectChatContext`.
339​
340### Approvals and generic interrupts
341​
342- A tool approval renders in the tool when you read the `interrupt` input.
343- To show it in the list instead, register a component under `interruptsComponents.tools` and render `Interrupts` in the layout.
344- Generic interrupts always render in the list. `generic.fallback` renders an unregistered id and an unbound interrupt. If the copy must be different, branch on `interrupt().kind === 'unbound'`.
345​
346### Show queued messages
347​
348Register `queue` on `components`, then render `Queue` in the layout. A queue component gets one `item` input. Call `item().cancelQueued()` to drop it.