Open History to see the last commit
1---
2title: "Quick Start: Angular"
3id: quick-start-angular
4order: 4
5description: "Build a streaming TanStack AI chat component in an Angular app using the injectChat function and the OpenAI adapter."
6keywords:
7 - tanstack ai
8 - angular
9 - quick start
10 - injectChat
11 - streaming chat
12 - openai
13 - signals
14---
15
16You have an Angular app and want to add AI chat. By the end of this guide, you'll have a streaming chat component powered by TanStack AI and OpenAI.
17
18> **Tip:** If you'd prefer not to sign up with individual AI providers, [OpenRouter](../adapters/openrouter) gives you access to 300+ models with a single API key and is the easiest way to get started.
19
20## Installation
21
22```bash
23npm install @tanstack/ai @tanstack/ai-angular @tanstack/ai-openai
24# or
25pnpm add @tanstack/ai @tanstack/ai-angular @tanstack/ai-openai
26# or
27yarn add @tanstack/ai @tanstack/ai-angular @tanstack/ai-openai
28```
29
30## Server Setup
31
32Angular apps typically use a separate backend. Here's an Express server that streams chat responses:
33
34```typescript ignore
35import express from 'express'
36import { chat, toServerSentEventsResponse } from '@tanstack/ai'
37import { openaiText } from '@tanstack/ai-openai'
38
39const app = express()
40app.use(express.json())
41
42app.post('/api/chat', async (req, res) => {
43 const { messages } = req.body
44
45 if (!process.env.OPENAI_API_KEY) {
46 res.status(500).json({ error: 'OPENAI_API_KEY not configured' })
47 return
48 }
49
50 try {
51 // `chat()` uses the AG-UI `threadId` for devtools correlation
52 // when available — no need to plumb `conversationId` manually.
53 const stream = chat({
54 adapter: openaiText('gpt-5.5'),
55 messages,
56 })
57
58 const response = toServerSentEventsResponse(stream)
59 res.writeHead(response.status, Object.fromEntries(response.headers))
60
61 const body = response.body
62 if (body) {
63 const reader = body.getReader()
64 const pump = async () => {
65 const { done, value } = await reader.read()
66 if (done) {
67 res.end()
68 return
69 }
70 res.write(value)
71 await pump()
72 }
73 await pump()
74 }
75 } catch (error) {
76 res.status(500).json({
77 error: error instanceof Error ? error.message : 'An error occurred',
78 })
79 }
80})
81
82app.listen(3000, () => console.log('Server running on port 3000'))
83```
84
85> **Tip:** Any backend that returns the TanStack AI SSE format works — you can use Fastify, Hono, Nitro, or any other Node.js framework.
86
87## Client Setup
88
89Create a standalone `ChatComponent` using the `injectChat` function:
90
91```typescript group=quick-start-angular
92import { Component, signal } from '@angular/core'
93import { FormsModule } from '@angular/forms'
94import { injectChat } from '@tanstack/ai-angular'
95import { fetchServerSentEvents } from '@tanstack/ai-client'
96
97@Component({
98 selector: 'app-chat',
99 standalone: true,
100 imports: [FormsModule],
101 template: `
102 <div class="chat">
103 <div class="messages">
104 @for (message of chat.messages(); track message.id) {
105 <div [class]="message.role">
106 <strong>{{ message.role === 'assistant' ? 'Assistant' : 'You' }}</strong>
107 @for (part of message.parts; track $index) {
108 @if (part.type === 'text') {
109 <p>{{ part.content }}</p>
110 }
111 }
112 </div>
113 }
114 </div>
115
116 <form (ngSubmit)="handleSubmit()">
117 <input
118 [(ngModel)]="input"
119 name="input"
120 placeholder="Type a message..."
121 [disabled]="chat.isLoading()"
122 />
123 <button
124 type="submit"
125 [disabled]="!input().trim() || chat.isLoading()"
126 >
127 Send
128 </button>
129 </form>
130 </div>
131 `,
132})
133export class ChatComponent {
134 // injectChat is called in a field initializer — this is a valid injection context.
135 chat = injectChat({
136 connection: fetchServerSentEvents('/api/chat'),
137 })
138
139 input = signal('')
140
141 handleSubmit() {
142 const text = this.input().trim()
143 if (text && !this.chat.isLoading()) {
144 this.chat.sendMessage(text)
145 this.input.set('')
146 }
147 }
148}
149```
150
151## Environment Variables
152
153Create a `.env` file (or `.env.local` depending on your setup) with your API key:
154
155```bash
156# OpenRouter (recommended — access 300+ models with one key)
157OPENROUTER_API_KEY=sk-or-...
158
159# OpenAI
160OPENAI_API_KEY=your-openai-api-key
161```
162
163Your server reads this key at runtime. Never expose it to the browser.
164
165## Angular-Specific Notes
166
167**State is exposed as Angular `Signal`s.** The `injectChat` function returns state wrapped in read-only `Signal`s. Read them by calling them as functions:
168
169```typescript ignore
170// In component class
171if (this.chat.isLoading()) { /* ... */ }
172const count = this.chat.messages().length
173
174// In template — same syntax, no .value needed
175```
176
177```html
178<!-- In template, call the signal as a function -->
179@if (chat.isLoading()) {
180 <p>Thinking...</p>
181}
182<span>{{ chat.messages().length }} messages</span>
183```
184
185**`injectChat` must be called in an injection context.** Angular's dependency injection requires that `inject()` is called during component construction. The recommended approach is a field initializer (shown above). You can also call it in the constructor or inside `runInInjectionContext`:
186
187```typescript
188import { injectChat } from '@tanstack/ai-angular'
189import { fetchServerSentEvents } from '@tanstack/ai-client'
190
191// Field initializer (recommended)
192export class MyComponentA {
193 chat = injectChat({ connection: fetchServerSentEvents('/api/chat') })
194}
195
196// Constructor
197export class MyComponentB {
198 chat: ReturnType<typeof injectChat>
199 constructor() {
200 this.chat = injectChat({ connection: fetchServerSentEvents('/api/chat') })
201 }
202}
203```
204
205Calling `injectChat` outside an injection context — for example, in a lifecycle hook like `ngOnInit` — will throw a runtime error.
206
207**Automatic cleanup.** The function subscribes to `DestroyRef` internally, so in-flight requests are stopped when the component is destroyed. No manual cleanup needed.
208
209**Same API shape as React and Vue.** If you're coming from `@tanstack/ai-react` or `@tanstack/ai-vue`, `injectChat` returns the same properties (`messages`, `sendMessage`, `isLoading`, `error`, `status`, `stop`, `reload`, `clear`). The only difference is that each property is an Angular `Signal` rather than a React state value or a Vue `ShallowRef`.
210
211## That's It!
212
213You now have a working Angular chat application. The `injectChat` function handles:
214
215- Message state management
216- Streaming responses
217- Loading states
218- Error handling
219
220## Next Steps
221
222- Learn about [Tools](../tools/tools) to add function calling
223- Check out the [Adapters](../adapters/openai) to connect to different providers
224- See the [React Quick Start](./quick-start) if you're comparing frameworks