
Syncfusion Angular Ai Assistview
- 212 installs
- Updated August 4, 2026
- syncfusion/angular-ui-components-skills
Use syncfusion-angular-ai-assistview for development tasks
About
syncfusion-angular-ai-assistview: A skill for development. This provides functionality for development workflows.
- syncfusion-angular-ai-assistview
Syncfusion Angular Ai Assistview by the numbers
- 212 all-time installs (skills.sh)
- +11 installs in the week ending Aug 5, 2026 (Skillselion tracking)
- Ranked #1,909 of 4,347 Backend & APIs skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/syncfusion/angular-ui-components-skills --skill syncfusion-angular-ai-assistviewAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 212 |
|---|---|
| Last updated | August 4, 2026 |
| Repository | syncfusion/angular-ui-components-skills ↗ |
What it does
Use syncfusion-angular-ai-assistview for development tasks
Files
Syncfusion Angular AI AssistView Component
Component Overview
The Syncfusion AI AssistView is a powerful Angular component that provides a ready-to-use interface for building conversational AI applications.
Key Capabilities:
- Conversation Management - Manage prompt-response pairs with history, persistence, and markdown rendering
- AI Service Integration - Connect to OpenAI, Gemini, Ollama, Lite-LLM, and MCP providers with streaming support
- Speech Features - Built-in speech-to-text with 11 configurable properties and 4 events
- Toolbar System - Four toolbar types (header, prompt, response, footer) with custom actions and tag directives
- View Management - Multiple views with programmatic
activeViewcontrol and dynamic switching - Events & Interactions - Typed event arguments (PromptRequestEventArgs, PromptChangedEventArgs, StopRespondingEventArgs)
- File Attachments - Support for file uploads with type/size restrictions and attachment click events
- Templates - Customize prompts, responses, suggestions, and banners with flexible templates
- Methods - Programmatically add/update responses, execute prompts, and control component behavior
- Globalization - Full RTL support and localization for 12+ languages with locale-based formatting
- Customizable UI - Height, width, CSS classes, HTML attributes, and theme customization
Documentation and Navigation Guide
Getting Started
📄 Read: references/getting-started.md
- Installation and dependency setup
- Angular environment configuration
- Basic component initialization
- CSS imports and theme configuration
- First working example
Core Features & Conversation Management
📄 Read: references/assist-view-basics.md
- Setting prompt text and placeholders
- Managing prompt-response collections
- Markdown response rendering
- Configuring prompt suggestions
- Customizing user and assistant avatars
- UI controls (clear button, scroll-to-bottom)
- Component configuration (height, width, showHeader, cssClass, htmlAttributes)
- State persistence with
enablePersistence - Globalization and localization (locale property with 12+ languages)
- RTL support with
enableRtlfor Arabic, Hebrew, Persian, Urdu
Appearance & Styling
📄 Read: references/appearance-customization.md
- Setting component width and height
- Applying custom CSS classes
- Theme customization
- Responsive design patterns
Multiple Views & Custom Content
📄 Read: references/custom-views.md
- Adding custom view models
- View types (Assist and Custom)
- View configuration and naming
- Managing multiple views within one component
- Programmatic view switching with
activeViewproperty - Dynamic view navigation patterns
- View history and breadcrumb navigation
- Workflow-based view switching
- Conditional view display based on user roles
Programmatic Control & Methods
📄 Read: references/methods-and-actions.md
- Adding prompt responses (string and object
- Complete event arguments reference section
- PromptRequestEventArgs with 6 properties (prompt, attachedFiles, promptSuggestions, cancel, etc.)
- PromptChangedEventArgs with 5 properties (value, previousValue, element, event)
- StopRespondingEventArgs for canceling responses
- AttachmentClickEventArgs with FileInfo interface
- Production-ready examples with all event types formats)
- Executing prompts dynamically
- Response handling patterns
- Programmatic interaction
Complete documentation for all 4 toolbar types
- Header Toolbar (
toolbarSettings) - Global actions and navigation - Prompt Toolbar (
promptToolbarSettings) - Actions on user prompts - Response Toolbar (
responseToolbarSettings) - Actions on AI responses - Footer Toolbar (
footerToolbarSettings) - Input area customization - ToolbarItemModel interface with 10 properties
- ToolbarItemClickedEventArgs with dataIndex handling
- Tag directive approach:
<e-toolbarsettings>,<e-toolbaritem> - Property binding approach for dynamic toolbar items
- Common patterns, best practices, and troubleshootingest, promptChanged)
- File upload events (beforeAttachmentUpload, attachmentUploadSuccess)
- Event handling patterns and best practices
File Attachments
📄 Read: references/file-attachments.md
- File attachment configuration
- Upload handling and validation
- File size and type restrictions
- Attachment display and management
Toolbar Configuration
📄 Read: references/toolbar-items.md
- Toolbar customization
- Built-in speech-to-text with
speechToTextSettings(recommended approach) - SpeechToTextSettingsModel with 11 configurable properties
- ButtonSettingsModel and TooltipSettingsModel interfaces
- 4 speech events: onStart, onStop, transcriptChanged, onError
- Event arguments: StartListeningEventArgs, StopListeningEventArgs, TranscriptChangedEventArgs, ErrorEventArgs
- Language support with 10+ language codes (en-US, es-ES, fr-FR, de-DE, ja-JP, etc.)
- Interim results handling with
allowInterimResults - Custom Web Speech API implementation (alternative approach)
- Text-to-speech setup and configuration
- Browser compatibility and error handling
Templates & Custom Rendering
📄 Read: references/templates.md
- Template system overview
- Prompt templates
- Response templates
- Custom template creation
AI Service Integration
📄 Read: references/ai-integrations.md
- Azure OpenAI integration setup
- Gemini integration
- Lite-LLM integration
- Model Context Protocol (MCP) integration
- Ollama integration
- Security best practices and API management
Speech Features
📄 Read: references/speech-features.md
- Speech-to-text setup and configuration
- Text-to-speech setup and configuration
- Audio handling
- Browser compatibility considerations
---
Quick Start Example
Here's a minimal working example to get started:
import { Component } from '@angular/core';
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[promptSuggestions]="suggestions"
(promptRequest)="onPromptRequest($event)">
</div>
`,
styles: [`
:host ::ng-deep #aiAssistView {
height: 100vh;
}
`]
})
export class AppComponent {
suggestions = [
'What is Angular?',
'How to create components?',
'Explain dependency injection'
];
onPromptRequest(args: any) {
// Handle prompt and provide response
setTimeout(() => {
const response = 'This is a sample response from your AI service.';
// Add response using component method
}, 1000);
}
}---
Common Patterns
Pattern 1: Basic Conversation Flow
1. Initialize component with suggestions 2. User enters prompt 3. promptRequest event fires 4. Call your AI service 5. Use addPromptResponse() to display result 6. Conversation history maintained automatically
Pattern 2: AI Service Integration with Streaming
1. Enable streaming with [enableStreaming]="true" 2. Configure AI provider credentials (OpenAI, Gemini, etc.) 3. In promptRequest event, call provider API with streaming 4. Use ReadableStream for chunked responses 5. Handle stopRespondingClick event for cancellation 6. Update UI with addPromptResponse() incrementally
Pattern 3: Custom View Management with activeView
1. Define multiple view types (Assist, Custom) 2. Use [activeView]="currentIndex" to control display 3. Switch between views programmatically based on user action 4. Track view history for back/forward navigation 5. Each view can have different configuration 6. Maintain separate state per view
Pattern 4: Complete Toolbar Configuration
1. Configure header toolbar for global actions (new chat, export, settings) 2. Set up prompt toolbar for user prompt actions (edit, copy, retry) 3. Add response toolbar for AI response actions (copy, regenerate, like/dislike) 4. Configure footer toolbar for input actions (formatting, attachments) 5. Use tag directive or property binding approach 6. Handle itemClicked events with dataIndex for context
Pattern 5: Speech-Enabled Interface
1. Configure speechToTextSettings with language and options 2. Enable allowInterimResults for real-time transcription 3. Handle speech events: onStart, onStop, transcriptChanged, onError 4. Automatically submit recognized text as prompts 5. Provide visual feedback during listening state
Pattern 6: Event-Driven Actions with Typed Arguments
1. Use PromptRequestEventArgs to access prompt, attachedFiles, and cancel flag 2. Use PromptChangedEventArgs for real-time input validation 3. Handle StopRespondingEventArgs to cancel long-running requests 4. Use beforeAttachmentUpload for file validation 5
Common Patterns
Pattern 1: Basic Conversation Flowstreaming responses, multi-language support, and toolbar actions
2. Code Assistant: Create coding helpers with syntax highlighting, code regeneration, and like/dislike feedback 3. Voice-Enabled Assistant: Implement hands-free interfaces with built-in speech-to-text in 10+ languages 4. Content Writer Assistant: Implement writing tools with grammar checking, real-time suggestions, and response streaming 5. Data Analysis Tool: Create interfaces with multiple views (query, results, visualization) and view switching 6. Learning Platform: Build educational assistants with RTL support for Arabic/Hebrew learners and persistent conversation history 7. Multi-language Support: Implement interfaces with locale configuration for 12+ languages and RTL text direction 8. Accessibility Assistant: Provide reading aid with speech features, keyboard navigation, and ARIA attributes 9. Workflow Applications: Build step-by-step wizards with programmatic view control and conditional navigation 10. Real-time AI Services: Integrate streaming AI providers with abort functionality and visual streaming indicatorser input | | promptSuggestions | string[] | [] | Provide quick starting prompts | | prompts | object[] | [] | Initialize conversation history | | showClearButton | boolean | false | Show button to clear input | | enableScrollToBottom | boolean | true | Show scroll-to-bottom indicator |
Layout & Appearance
| Property | Type | Default | When to Use |
|---|---|---|---|
width | string \ | number | '100%' |
height | string \ | number | '100%' |
cssClass | string | '' | Apply custom CSS styling and themes |
showHeader | boolean | true | Control header visibility |
htmlAttributes | object | {} | Add custom HTML attributes (aria-, data-, etc.) |
Streaming & Features
| Property | Type | Default | When to Use |
|---|---|---|---|
enableStreaming | boolean | false | Enable real-time streaming responses |
speechToTextSettings | SpeechToTextSettingsModel | null | Configure built-in speech recognition |
activeView | number | 0 | Programmatically switch between views |
Globalization
| Property | Type | Default | When to Use |
|---|---|---|---|
locale | string | 'en-US' | Set language/culture (en-US, es-ES, fr-FR, de-DE, ja-JP, ar-SA, etc.) |
enableRtl | boolean | false | Enable right-to-left text direction (Arabic, Hebrew, Persian, Urdu) |
enablePersistence | boolean | false | Save component state between page reloads |
Toolbar Configuration
| Property | Type | Default | When to Use |
|---|---|---|---|
toolbarSettings | ToolbarSettingsModel | null | Configure header toolbar (global actions) |
promptToolbarSettings | PromptToolbarSettingsModel | null | Configure prompt toolbar (edit, copy, retry) |
responseToolbarSettings | ResponseToolbarSettingsModel | null | Configure response toolbar (copy, regenerate, like/dislike) |
footerToolbarSettings | FooterToolbarSettingsModel | null | Configure footer toolbar (formatting, attachments) |
Pattern 3: Custom View Management
1. Define multiple view types (Assist, Custom) 2. Switch between views based on user action 3. Each view can have different configuration 4. Maintain separate state per view
Pattern 4: Event-Driven Actions
1. Listen to promptChanged for input validation 2. Handle beforeAttachmentUpload for file validation 3. Use attachmentUploadSuccess for post-upload actions 4. Leverage created event for initialization
---
Key Properties
| Property | Type | Default | When to Use |
|---|---|---|---|
prompt | string | '' | Pre-fill prompt text |
promptPlaceholder | string | 'Type prompt for assistance...' | Guide user input |
promptSuggestions | string[] | [] | Provide quick starting prompts |
prompts | object[] | [] | Initialize conversation history |
width | string | '100%' | Set container width |
height | string | '100%' | Set container height |
cssClass | string | '' | Apply custom CSS styling |
showClearButton | boolean | false | Show button to clear input |
enableScrollToBottom | boolean | true | Show scroll-to-bottom indicator |
---
Common Use Cases
1. Customer Support Chatbot: Build customer service interfaces with knowledge base integration 2. Code Assistant: Create coding helpers with AI that can review and suggest code 3. Content Writer Assistant: Implement writing tools with grammar and style suggestions 4. Data Analysis Tool: Create interfaces for users to query and analyze data through natural language 5. Learning Platform: Build educational assistants that answer student questions 6. Internal Knowledge Bot: Create enterprise assistants for company documentation and FAQs 7. Multi-language Support: Implement translation and localization features 8. Accessibility Assistant: Provide reading aid or instruction assistance
---
AI Service Integration Guide
Table of Contents
- Integration Overview
- Azure OpenAI Integration
- Gemini Integration
- Lite-LLM Integration
- Model Context Protocol (MCP) Integration
- Ollama Integration
- Security Best Practices
---
Integration Overview
The AI AssistView component integrates seamlessly with multiple AI service providers. Each integration requires proper configuration, API credentials, and secure handling of sensitive information.
General Integration Pattern
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
(promptRequest)="onPromptRequest($event)">
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
async onPromptRequest(args: any) {
const userPrompt = args.prompt;
try {
// Call your AI service
const response = await this.callAIService(userPrompt);
// Display response in component
this.aiAssistViewComponent.addPromptResponse(response);
} catch (error) {
console.error('AI service error:', error);
const errorMessage = 'Sorry, I encountered an error processing your request.';
this.aiAssistViewComponent.addPromptResponse(errorMessage);
}
}
private async callAIService(prompt: string): Promise<string> {
// Implementation depends on chosen provider
return '';
}
}---
Azure OpenAI Integration
Integrate Azure OpenAI to leverage GPT models:
Prerequisites
- Azure Account with Azure OpenAI resource
- API Key and Endpoint from Azure Portal
- Deployment name (e.g., gpt-4o-mini)
- API version
Implementation
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewModule, AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
(promptRequest)="onPromptRequest($event)">
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
private readonly AZURE_API_KEY = 'your-api-key';
private readonly AZURE_ENDPOINT = 'https://your-resource.openai.azure.com';
private readonly AZURE_DEPLOYMENT = 'gpt-4o-mini';
private readonly AZURE_API_VERSION = '2024-08-01-preview';
async onPromptRequest(args: any) {
const userPrompt = args.prompt;
try {
const response = await this.callAzureOpenAI(userPrompt);
this.aiAssistViewComponent.addPromptResponse(response);
} catch (error) {
this.aiAssistViewComponent.addPromptResponse('Error: Unable to process your request.');
}
}
private async callAzureOpenAI(prompt: string): Promise<string> {
const url = `${this.AZURE_ENDPOINT}/openai/deployments/${this.AZURE_DEPLOYMENT}/chat/completions?api-version=${this.AZURE_API_VERSION}`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'api-key': this.AZURE_API_KEY
},
body: JSON.stringify({
messages: [
{
role: 'user',
content: prompt
}
],
temperature: 0.7,
max_tokens: 800
})
});
if (!response.ok) {
throw new Error(`Azure OpenAI error: ${response.statusText}`);
}
const data = await response.json();
return data.choices[0].message.content;
}
}Security Note
Never expose API keys in client-side code. Use a backend proxy or environment variables:
// In environment.ts
export const environment = {
production: false,
aiServiceUrl: 'http://localhost:3000/api/ai' // Backend proxy
};
// In component
private readonly AI_SERVICE_URL = environment.aiServiceUrl;
async callAIService(prompt: string): Promise<string> {
const response = await fetch(`${this.AI_SERVICE_URL}/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt })
});
const data = await response.json();
return data.response;
}---
Gemini Integration
Integrate Google's Gemini API:
Setup
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
(promptRequest)="onPromptRequest($event)">
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
private readonly GEMINI_API_KEY = 'your-gemini-api-key';
private readonly GEMINI_API_URL = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent';
async onPromptRequest(args: any) {
const userPrompt = args.prompt;
try {
const response = await this.callGeminiAPI(userPrompt);
this.aiAssistViewComponent.addPromptResponse(response);
} catch (error) {
this.aiAssistViewComponent.addPromptResponse('Error: Gemini API call failed.');
}
}
private async callGeminiAPI(prompt: string): Promise<string> {
const url = `${this.GEMINI_API_URL}?key=${this.GEMINI_API_KEY}`;
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
contents: [
{
parts: [
{
text: prompt
}
]
}
],
generationConfig: {
temperature: 0.7,
maxOutputTokens: 800
}
})
});
if (!response.ok) {
throw new Error(`Gemini API error: ${response.statusText}`);
}
const data = await response.json();
return data.candidates[0].content.parts[0].text;
}
}---
Lite-LLM Integration
Use Lite-LLM for unified access to multiple LLM providers:
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
(promptRequest)="onPromptRequest($event)">
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
private readonly LITE_LLM_API_KEY = 'your-lite-llm-key';
private readonly LITE_LLM_URL = 'http://localhost:4000'; // Local Lite-LLM server
async onPromptRequest(args: any) {
const userPrompt = args.prompt;
try {
const response = await this.callLiteLLM(userPrompt);
this.aiAssistViewComponent.addPromptResponse(response);
} catch (error) {
this.aiAssistViewComponent.addPromptResponse('Error: Lite-LLM call failed.');
}
}
private async callLiteLLM(prompt: string): Promise<string> {
const response = await fetch(`${this.LITE_LLM_URL}/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.LITE_LLM_API_KEY}`
},
body: JSON.stringify({
model: 'gpt-3.5-turbo', // Or any model supported by Lite-LLM
messages: [
{
role: 'user',
content: prompt
}
],
temperature: 0.7
})
});
if (!response.ok) {
throw new Error(`Lite-LLM error: ${response.statusText}`);
}
const data = await response.json();
return data.choices[0].message.content;
}
}---
Model Context Protocol (MCP) Integration
Integrate with Model Context Protocol for structured interactions:
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
(promptRequest)="onPromptRequest($event)">
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
private mcpClient: any; // MCP client instance
async ngOnInit() {
// Initialize MCP client
this.initializeMCP();
}
private initializeMCP() {
// Initialize your MCP client
// Example: this.mcpClient = new MCPClient('server-config');
}
async onPromptRequest(args: any) {
const userPrompt = args.prompt;
try {
const response = await this.callMCP(userPrompt);
this.aiAssistViewComponent.addPromptResponse(response);
} catch (error) {
this.aiAssistViewComponent.addPromptResponse('Error: MCP interaction failed.');
}
}
private async callMCP(prompt: string): Promise<string> {
// Call MCP endpoint
const result = await this.mcpClient.request({
method: 'call_tool',
params: {
tool: 'chat',
input: {
message: prompt
}
}
});
return result.output || 'No response received.';
}
}---
Ollama Integration
Integrate with local Ollama LLM service:
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
(promptRequest)="onPromptRequest($event)">
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
private readonly OLLAMA_URL = 'http://localhost:11434';
private readonly MODEL = 'llama2'; // or other available model
async onPromptRequest(args: any) {
const userPrompt = args.prompt;
try {
const response = await this.callOllama(userPrompt);
this.aiAssistViewComponent.addPromptResponse(response);
} catch (error) {
this.aiAssistViewComponent.addPromptResponse('Error: Ollama service unavailable.');
}
}
private async callOllama(prompt: string): Promise<string> {
const response = await fetch(`${this.OLLAMA_URL}/api/generate`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: this.MODEL,
prompt: prompt,
stream: false,
temperature: 0.7
})
});
if (!response.ok) {
throw new Error(`Ollama error: ${response.statusText}`);
}
const data = await response.json();
return data.response;
}
}---
Security Best Practices
1. Protect API Keys
// ❌ DO NOT: Expose keys in client code
const apiKey = 'sk-your-actual-key';
// ✅ DO: Use backend proxy
const response = await fetch('/api/chat', {
method: 'POST',
body: JSON.stringify({ prompt })
});2. Use Environment Variables
// environment.ts
export const environment = {
apiEndpoint: 'https://api.example.com'
};
// component.ts
import { environment } from '../environments/environment';
const endpoint = environment.apiEndpoint;3. Implement Rate Limiting
private lastRequestTime = 0;
private readonly REQUEST_DELAY = 1000; // 1 second minimum
async onPromptRequest(args: any) {
const now = Date.now();
if (now - this.lastRequestTime < this.REQUEST_DELAY) {
this.aiAssistViewComponent.addPromptResponse('Please wait before sending another prompt.');
return;
}
this.lastRequestTime = now;
// Process prompt
}4. Validate and Sanitize Input
private sanitizeInput(input: string): string {
return input
.trim()
.substring(0, 5000) // Limit length
.replace(/<[^>]*>/g, ''); // Remove HTML tags
}
async onPromptRequest(args: any) {
const sanitized = this.sanitizeInput(args.prompt);
// Use sanitized prompt
}5. Handle Errors Gracefully
async callAIService(prompt: string): Promise<string> {
try {
// API call
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('401')) {
return 'Authentication failed. Please check your credentials.';
} else if (error.message.includes('429')) {
return 'Too many requests. Please try again later.';
}
}
return 'An unexpected error occurred. Please try again.';
}
}---
Streaming Responses
For providers supporting streaming, update responses progressively:
async onPromptRequest(args: any) {
const userPrompt = args.prompt;
let accumulatedResponse = '';
try {
const response = await fetch('your-api-endpoint', {
method: 'POST',
body: JSON.stringify({ prompt: userPrompt })
});
if (!response.body) return;
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
accumulatedResponse += chunk;
// Update UI with accumulated response
this.aiAssistViewComponent.addPromptResponse(accumulatedResponse);
}
} catch (error) {
this.aiAssistViewComponent.addPromptResponse('Streaming error occurred.');
}
}Appearance and Styling Customization
Setting Component Width
The width property defines the width of the AI AssistView container. You can set this as a string using pixels (e.g., "500px") or percentage (e.g., "50%"). The default is "100%", filling the parent container.
Fixed Width Example
import { Component } from '@angular/core';
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[width]="'800px'">
</div>
`
})
export class AppComponent { }Responsive Width
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[width]="'100%'"
style="max-width: 1200px; margin: 0 auto;">
</div>
`
})
export class AppComponent { }Percentage-Based Width
template: `
<div class="container">
<div ejs-aiassistview
id='aiAssistView'
[width]="'75%'">
</div>
</div>
`
styles: [`
.container {
display: flex;
width: 100%;
}
.container ::ng-deep #aiAssistView {
border-right: 1px solid #e0e0e0;
}
`]---
Setting Component Height
The height property defines the height of the AI AssistView container. You can specify it as pixels (e.g., "600px") or percentage (e.g., "100%"). The default is "100%".
Fixed Height Example
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[height]="'600px'">
</div>
`
})
export class AppComponent { }Full Viewport Height
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[height]="'100vh'">
</div>
`,
styles: [`
:host {
display: block;
height: 100vh;
}
`]
})
export class AppComponent { }Responsive Height
import { ViewChild, HostListener } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
[height]="componentHeight">
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
componentHeight = '600px';
@HostListener('window:resize', ['$event'])
onResize(event: Event) {
const windowHeight = window.innerHeight;
const headerHeight = 60; // Adjust based on your layout
this.componentHeight = (windowHeight - headerHeight) + 'px';
}
}---
Applying Custom CSS Styles
The cssClass property applies one or more custom CSS classes to the AI AssistView component's root element, enabling advanced style customization.
Single CSS Class
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[cssClass]="'custom-theme'">
</div>
`,
styles: [`
:host ::ng-deep .custom-theme {
border: 2px solid #2196F3;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
:host ::ng-deep .custom-theme .e-prompt-input {
border-radius: 0 0 8px 8px;
}
`]
})
export class AppComponent { }Multiple CSS Classes
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[cssClass]="'dark-theme bordered-style'"
[width]="'100%'"
[height]="'100vh'">
</div>
`,
styles: [`
:host ::ng-deep .dark-theme {
background-color: #1e1e1e;
color: #ffffff;
}
:host ::ng-deep .dark-theme .e-prompt-input {
background-color: #2d2d2d;
color: #ffffff;
border: 1px solid #404040;
}
:host ::ng-deep .bordered-style {
border: 1px solid #404040;
border-radius: 4px;
}
`]
})
export class AppComponent { }Advanced Styling Example
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[cssClass]="'premium-style'"
[promptSuggestions]="suggestions">
</div>
`,
styles: [`
:host ::ng-deep .premium-style {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 12px;
overflow: hidden;
box-shadow: 0 8px 32px rgba(0,0,0,0.1);
}
:host ::ng-deep .premium-style .e-assistview-container {
background: #ffffff;
border-radius: 12px;
}
:host ::ng-deep .premium-style .e-prompt-input {
background: #f5f5f5;
border: 2px solid #e0e0e0;
border-radius: 8px;
padding: 12px;
font-size: 16px;
}
:host ::ng-deep .premium-style .e-prompt-input:focus {
border-color: #667eea;
outline: none;
}
:host ::ng-deep .premium-style .e-response {
padding: 12px;
border-radius: 8px;
background: #f9f9f9;
margin: 8px 0;
}
`]
})
export class AppComponent {
suggestions = [
'Start a new conversation',
'View conversation history',
'Export conversation'
];
}---
Theme Customization
Using Built-in Themes
The Syncfusion components support multiple built-in themes. Change the CSS import in styles.css:
/* Material 3 (Default) */
@import "../node_modules/@syncfusion/ej2-base/styles/material3.css";
@import '../node_modules/@syncfusion/ej2-interactive-chat/styles/material3.css';
/* Or Bootstrap 5 */
@import "../node_modules/@syncfusion/ej2-base/styles/bootstrap5.css";
@import '../node_modules/@syncfusion/ej2-interactive-chat/styles/bootstrap5.css';
/* Or Fabric */
@import "../node_modules/@syncfusion/ej2-base/styles/fabric.css";
@import '../node_modules/@syncfusion/ej2-interactive-chat/styles/fabric.css';
/* Or Tailwind */
@import "../node_modules/@syncfusion/ej2-base/styles/tailwind.css";
@import '../node_modules/@syncfusion/ej2-interactive-chat/styles/tailwind.css';Combining Custom Styles with Themes
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[cssClass]="'my-custom-overrides'">
</div>
`,
styles: [`
:host ::ng-deep .my-custom-overrides {
/* Override theme colors */
--primary-color: #3f51b5;
--surface-color: #ffffff;
--text-color: #212121;
}
:host ::ng-deep .my-custom-overrides .e-prompt-input {
padding: 16px;
font-size: 14px;
line-height: 1.5;
}
`]
})
export class AppComponent { }---
Responsive Design
Mobile-First Approach
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div class="responsive-container">
<div ejs-aiassistview
id='aiAssistView'
[width]="'100%'"
[height]="'100vh'">
</div>
</div>
`,
styles: [`
.responsive-container {
width: 100%;
height: 100vh;
}
/* Mobile */
@media (max-width: 768px) {
:host ::ng-deep #aiAssistView {
font-size: 14px;
}
:host ::ng-deep .e-prompt-input {
padding: 12px;
}
}
/* Tablet */
@media (min-width: 768px) and (max-width: 1024px) {
:host ::ng-deep #aiAssistView {
font-size: 15px;
}
}
/* Desktop */
@media (min-width: 1024px) {
:host ::ng-deep #aiAssistView {
font-size: 16px;
max-width: 1400px;
margin: 0 auto;
}
}
`]
})
export class AppComponent { }Sidebar Layout
template: `
<div class="layout">
<aside class="sidebar">
<h3>Conversations</h3>
<ul>
<li>Conversation 1</li>
<li>Conversation 2</li>
</ul>
</aside>
<main class="content">
<div ejs-aiassistview
id='aiAssistView'
[width]="'100%'"
[height]="'100%'">
</div>
</main>
</div>
`,
styles: [`
.layout {
display: flex;
height: 100vh;
}
.sidebar {
width: 250px;
border-right: 1px solid #e0e0e0;
overflow-y: auto;
}
.content {
flex: 1;
display: flex;
flex-direction: column;
}
`]AI AssistView Basics: Core Features and Conversation Management
Table of Contents
- Setting Prompt Text
- Prompt Placeholder
- Prompt-Response Collection
- Markdown Response Rendering
- Configuring Suggestions
- Avatar Customization
- UI Controls
- Component Configuration
- Globalization and Localization
---
Setting Prompt Text
The prompt property allows you to define initial or default text that appears in the prompt input area. This is useful for pre-filling the input with context or guidance.
Basic Usage
import { Component } from '@angular/core';
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[prompt]="initialPrompt">
</div>
`
})
export class AppComponent {
initialPrompt = 'Please analyze this data...';
}When to Use
- Pre-populate input with context from previous interactions
- Set default instruction text for users
- Provide template prompts for common queries
---
Prompt Placeholder
The promptPlaceholder property defines the placeholder text displayed in the prompt textarea when it's empty. The default is "Type prompt for assistance...".
Customization Example
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[promptPlaceholder]="'Ask me anything about your code...'">
</div>
`
})
export class AppComponent { }Best Practices
- Keep placeholder text concise (under 50 characters)
- Make it specific to your use case
- Guide users on expected input format if needed
---
Prompt-Response Collection
The prompts property enables you to initialize the component with pre-configured conversation data or retrieve the complete history of user interactions. This automatically stores all user inputs and corresponding AI responses.
Initialize with Conversation History
interface PromptItem {
prompt: string;
response: string;
}
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[prompts]="conversationHistory">
</div>
`
})
export class AppComponent {
conversationHistory: PromptItem[] = [
{
prompt: 'What is Angular?',
response: 'Angular is a TypeScript-based open-source web application framework...'
},
{
prompt: 'How do components work?',
response: 'Components are the basic building blocks of Angular applications...'
}
];
}Retrieve Conversation History
import { ViewChild } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
// ... component config
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
saveConversation() {
const history = this.aiAssistViewComponent.prompts;
console.log('Current conversation:', history);
// Save to storage or send to server
}
}Use Cases
- Resume conversations from previous sessions
- Load context-specific conversation starters
- Maintain conversation history across page refreshes
---
Markdown Response Rendering
The AI AssistView supports rendering responses as Markdown content, which is automatically converted to HTML using the built-in Markdown Converter. The streaming of markdown content happens seamlessly with dynamic rendering support.
Supported Markdown Features
const markdownResponse = `
# Heading 1
## Heading 2
This is **bold** and this is *italic*.
- List item 1
- List item 2
- List item 3
\`\`\`typescript
const greeting = 'Hello, World!';
console.log(greeting);
\`\`\`
[Link to Syncfusion](https://www.syncfusion.com)
`;Example: Streaming Markdown Response
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
(promptRequest)="onPromptRequest($event)">
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
onPromptRequest(args: any) {
// Example markdown response
const markdownContent = `
## Summary
You asked about **Angular forms**.
### Key Points:
1. Template-driven forms
2. Reactive forms
3. Form validation
### Example Code:
\`\`\`typescript
import { FormBuilder } from '@angular/forms';
constructor(private fb: FormBuilder) {}
\`\`\`
`;
setTimeout(() => {
this.aiAssistViewComponent.addPromptResponse(markdownContent);
}, 1000);
}
}Supported Markdown Syntax
- Headers: # to ######
- Bold: text or __text__
- Italic: text or _text_
- Lists: - or * for unordered, 1. for ordered
- Code blocks: \
\\language code \\\ - Inline code: \
code\ - Links: text
- Blockquotes: > text
---
Configuring Suggestions
The promptSuggestions property provides users with helpful suggestions that appear initially or on-demand. These guide users to discover available functionality.
Basic Suggestions
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[promptSuggestions]="suggestions">
</div>
`
})
export class AppComponent {
suggestions = [
'What is TypeScript?',
'Show Angular best practices',
'How to create services?',
'Explain dependency injection',
'What are pipes?'
];
}Customizing Suggestions Header
Use promptSuggestionsHeader to add descriptive header text:
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[promptSuggestions]="suggestions"
[promptSuggestionsHeader]="'Suggested Topics'">
</div>
`
})
export class AppComponent {
suggestions = [
'Getting Started with Angular',
'Component Architecture',
'State Management',
'Testing Strategies'
];
}Best Practices
- Keep 3-5 suggestions initially
- Make suggestions specific and actionable
- Update suggestions based on context
- Group related topics together
---
Avatar Customization
User Avatar Customization
The promptIconCss property enables customization of the user avatar icon appearing alongside user prompts.
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[promptIconCss]="'e-icon-user'"
style="height: 100vh">
</div>
`
})
export class AppComponent { }AI Assistant Avatar
The responseIconCss property allows customization of the AI assistant avatar appearing alongside responses. By default, e-assistview-icon is used.
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[responseIconCss]="'e-icon-robot'">
</div>
`
})
export class AppComponent { }Custom CSS Class Example
// Component template
template: `
<div ejs-aiassistview
id='aiAssistView'
[promptIconCss]="'custom-user-icon'"
[responseIconCss]="'custom-assistant-icon'">
</div>
`
// Add CSS
styles: [`
:host ::ng-deep .custom-user-icon::before {
content: '👤';
font-size: 18px;
}
:host ::ng-deep .custom-assistant-icon::before {
content: '🤖';
font-size: 18px;
}
`]---
UI Controls
Clear Button
The showClearButton property controls the visibility of the clear button in the prompt input area. Default is false.
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[showClearButton]="true">
</div>
`
})
export class AppComponent { }Note: When the clear button is clicked, only the current prompt text is cleared, while the conversation history remains intact.
Scroll-to-Bottom Indicator
The enableScrollToBottom property shows or hides the scroll-to-bottom indicator. Default is true.
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[enableScrollToBottom]="true">
</div>
`
})
export class AppComponent { }When enabled, a floating icon appears when the user scrolls away from the bottom. Clicking it smoothly scrolls the view to display the latest response.
Practical Example
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[promptSuggestions]="suggestions"
[promptSuggestionsHeader]="'What can I help you with?'"
[promptPlaceholder]="'Type your question here...'"
[showClearButton]="true"
[enableScrollToBottom]="true"
(promptRequest)="onPromptRequest($event)">
</div>
`,
styles: [`
:host ::ng-deep #aiAssistView {
height: 100vh;
border: 1px solid #e0e0e0;
}
`]
})
export class AppComponent {
suggestions = ['Hello', 'Help', 'Examples'];
onPromptRequest(args: any) {
// Handle prompt
}
}---
Component Configuration
Height and Width
Control the dimensions of the AI AssistView component using the height and width properties.
Default Values:
height: '100%'width: '100%'
Fixed Dimensions
import { Component } from '@angular/core';
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[height]="'600px'"
[width]="'800px'">
</div>
`
})
export class AppComponent { }Responsive Dimensions
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div class="ai-container">
<div ejs-aiassistview
id='aiAssistView'
[height]="'100%'"
[width]="'100%'">
</div>
</div>
`,
styles: [`
.ai-container {
height: calc(100vh - 60px);
width: 100%;
max-width: 1200px;
margin: 0 auto;
padding: 16px;
}
`]
})
export class AppComponent { }Dynamic Sizing
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div class="controls">
<button (click)="setSize('small')">Small</button>
<button (click)="setSize('medium')">Medium</button>
<button (click)="setSize('large')">Large</button>
</div>
<div ejs-aiassistview
id='aiAssistView'
[height]="componentHeight"
[width]="componentWidth">
</div>
`
})
export class AppComponent {
componentHeight = '600px';
componentWidth = '800px';
setSize(size: string) {
switch (size) {
case 'small':
this.componentHeight = '400px';
this.componentWidth = '600px';
break;
case 'medium':
this.componentHeight = '600px';
this.componentWidth = '800px';
break;
case 'large':
this.componentHeight = '800px';
this.componentWidth = '1200px';
break;
}
}
}---
Show Header
The showHeader property controls the visibility of the component header. By default, it's true.
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[showHeader]="false">
</div>
`
})
export class AppComponent { }When to hide the header:
- Embedding in a custom layout with your own header
- Creating a minimalist interface
- Building a mobile-optimized view
Example with Custom Header:
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div class="custom-layout">
<div class="custom-header">
<h2>AI Assistant</h2>
<button (click)="clearChat()">Clear Chat</button>
</div>
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
[showHeader]="false"
(promptRequest)="onPromptRequest($event)">
</div>
</div>
`,
styles: [`
.custom-layout {
display: flex;
flex-direction: column;
height: 100vh;
}
.custom-header {
padding: 16px;
background: #2196F3;
color: white;
display: flex;
justify-content: space-between;
align-items: center;
}
.custom-header h2 {
margin: 0;
}
.custom-header button {
padding: 8px 16px;
background: white;
color: #2196F3;
border: none;
border-radius: 4px;
cursor: pointer;
}
`]
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
clearChat() {
// Clear conversation logic
}
onPromptRequest(args: any) {
setTimeout(() => {
this.aiAssistViewComponent.addPromptResponse('Response...');
}, 1000);
}
}---
CSS Class Customization
The cssClass property allows you to apply custom CSS classes to the AI AssistView component for styling and theming.
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[cssClass]="'custom-theme dark-mode'">
</div>
`,
styles: [`
:host ::ng-deep .custom-theme {
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
:host ::ng-deep .custom-theme.dark-mode {
background: #1e1e1e;
color: #ffffff;
}
:host ::ng-deep .custom-theme.dark-mode .e-assistview-prompt {
background: #2d2d2d;
border-color: #3d3d3d;
}
:host ::ng-deep .custom-theme.dark-mode .e-assistview-response {
background: #252525;
}
`]
})
export class AppComponent { }Common Use Cases:
- Theme switching (light/dark mode)
- Brand-specific styling
- Responsive design variations
- Accessibility enhancements
Multiple Classes Example:
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div class="theme-toggle">
<button (click)="toggleTheme()">Toggle Theme</button>
</div>
<div ejs-aiassistview
id='aiAssistView'
[cssClass]="currentThemeClass">
</div>
`,
styles: [`
:host ::ng-deep .light-theme {
background: #ffffff;
color: #333333;
}
:host ::ng-deep .dark-theme {
background: #1e1e1e;
color: #ffffff;
}
:host ::ng-deep .compact-mode {
font-size: 14px;
line-height: 1.4;
}
:host ::ng-deep .compact-mode .e-assistview-prompt,
:host ::ng-deep .compact-mode .e-assistview-response {
padding: 8px;
margin: 4px 0;
}
`]
})
export class AppComponent {
isDarkMode = false;
currentThemeClass = 'light-theme compact-mode';
toggleTheme() {
this.isDarkMode = !this.isDarkMode;
this.currentThemeClass = this.isDarkMode
? 'dark-theme compact-mode'
: 'light-theme compact-mode';
}
}---
HTML Attributes
The htmlAttributes property allows you to add custom HTML attributes to the AI AssistView component's root element.
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[htmlAttributes]="customAttributes">
</div>
`
})
export class AppComponent {
customAttributes = {
'data-component': 'ai-assistant',
'data-version': '1.0',
'aria-label': 'AI Assistant Chat Interface',
'role': 'application',
'tabindex': '0'
};
}Common Use Cases:
Accessibility Attributes
customAttributes = {
'aria-label': 'AI Powered Assistant',
'aria-describedby': 'ai-description',
'role': 'application'
};Data Attributes for Analytics
customAttributes = {
'data-tracking-id': 'ai-chat-v2',
'data-user-type': 'premium',
'data-region': 'us-west'
};Custom Element Attributes
customAttributes = {
'data-theme': 'corporate',
'data-module': 'customer-support',
'title': 'AI Support Assistant'
};---
State Persistence
The enablePersistence property enables the component to save its state (conversation history, settings) between page reloads. Default is false.
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[enablePersistence]="true"
(promptRequest)="onPromptRequest($event)">
</div>
`
})
export class AppComponent {
onPromptRequest(args: any) {
// Conversation is automatically saved to localStorage
}
}What Gets Persisted:
- Conversation history (prompts and responses)
- Active view index
- Component state
Storage Location: Browser's localStorage with the component ID as the key.
Example with Custom ID:
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='userChatSession123'
[enablePersistence]="true">
</div>
`
})
export class AppComponent {
// State is saved with key: 'userChatSession123'
}Clear Persisted Data:
import { Component, ViewChild, OnInit } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<button (click)="clearPersistedData()">Clear Saved Data</button>
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
[enablePersistence]="true">
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
clearPersistedData() {
// Clear from localStorage
localStorage.removeItem('aiAssistView');
// Optionally reload the page to reset the component
window.location.reload();
}
}---
Globalization and Localization
Locale Configuration
The locale property enables you to set the language and regional settings for the AI AssistView component. Default is 'en-US' (English - United States).
Basic Localization
import { Component } from '@angular/core';
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { L10n, setCulture } from '@syncfusion/ej2-base';
// Set culture globally
setCulture('de-DE');
// Load German translations
L10n.load({
'de-DE': {
'aiassistview': {
'promptPlaceholder': 'Geben Sie hier Ihre Frage ein...',
'sendButton': 'Senden',
'clearButton': 'Löschen'
}
}
});
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[locale]="'de-DE'">
</div>
`
})
export class AppComponent { }Multi-Language Support
import { Component } from '@angular/core';
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { L10n } from '@syncfusion/ej2-base';
// Load multiple language translations
L10n.load({
'fr-FR': {
'aiassistview': {
'promptPlaceholder': 'Tapez votre question ici...',
'sendButton': 'Envoyer',
'clearButton': 'Effacer'
}
},
'es-ES': {
'aiassistview': {
'promptPlaceholder': 'Escribe tu pregunta aquí...',
'sendButton': 'Enviar',
'clearButton': 'Borrar'
}
},
'ja-JP': {
'aiassistview': {
'promptPlaceholder': 'ここに質問を入力してください...',
'sendButton': '送信',
'clearButton': 'クリア'
}
}
});
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div class="language-selector">
<button (click)="setLanguage('en-US')">English</button>
<button (click)="setLanguage('fr-FR')">Français</button>
<button (click)="setLanguage('es-ES')">Español</button>
<button (click)="setLanguage('ja-JP')">日本語</button>
</div>
<div ejs-aiassistview
id='aiAssistView'
[locale]="currentLocale">
</div>
`
})
export class AppComponent {
currentLocale = 'en-US';
setLanguage(locale: string) {
this.currentLocale = locale;
}
}Available Locales
Common locale codes:
en-US- English (United States)en-GB- English (United Kingdom)de-DE- German (Germany)fr-FR- French (France)es-ES- Spanish (Spain)it-IT- Italian (Italy)pt-BR- Portuguese (Brazil)zh-CN- Chinese (Simplified)ja-JP- Japaneseko-KR- Koreanar-SA- Arabic (Saudi Arabia)ru-RU- Russian
---
Right-to-Left (RTL) Support
The enableRtl property enables right-to-left text direction for languages like Arabic, Hebrew, and Urdu. Default is false.
Basic RTL Configuration
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[enableRtl]="true"
[locale]="'ar-SA'">
</div>
`
})
export class AppComponent { }RTL with Arabic Localization
import { Component } from '@angular/core';
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { L10n, setCulture } from '@syncfusion/ej2-base';
// Set RTL culture
setCulture('ar-SA');
// Load Arabic translations
L10n.load({
'ar-SA': {
'aiassistview': {
'promptPlaceholder': 'اكتب سؤالك هنا...',
'sendButton': 'إرسال',
'clearButton': 'مسح'
}
}
});
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[enableRtl]="true"
[locale]="'ar-SA'"
[promptPlaceholder]="'اكتب سؤالك هنا...'">
</div>
`
})
export class AppComponent { }Dynamic RTL Toggle
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div class="direction-toggle">
<button (click)="toggleDirection()">
{{ isRtl ? 'Switch to LTR' : 'Switch to RTL' }}
</button>
</div>
<div ejs-aiassistview
id='aiAssistView'
[enableRtl]="isRtl"
[locale]="currentLocale">
</div>
`
})
export class AppComponent {
isRtl = false;
currentLocale = 'en-US';
toggleDirection() {
this.isRtl = !this.isRtl;
this.currentLocale = this.isRtl ? 'ar-SA' : 'en-US';
}
}RTL Languages Support
Languages that typically use RTL:
- Arabic (ar-*): Arabic dialects
- Hebrew (he-IL): Hebrew (Israel)
- Urdu (ur-PK): Urdu (Pakistan)
- Persian (fa-IR): Persian (Iran)
- Yiddish (yi): Yiddish
Complete RTL Example:
import { Component } from '@angular/core';
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { L10n } from '@syncfusion/ej2-base';
L10n.load({
'he-IL': {
'aiassistview': {
'promptPlaceholder': 'הקלד את שאלתך כאן...',
'sendButton': 'שלח',
'clearButton': 'נקה'
}
}
});
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
id='aiAssistView'
[enableRtl]="true"
[locale]="'he-IL'"
[promptSuggestions]="hebrewSuggestions"
[promptPlaceholder]="'הקלד את שאלתך כאן...'"
(promptRequest)="onPromptRequest($event)">
</div>
`,
styles: [`
:host ::ng-deep #aiAssistView {
font-family: 'Arial', sans-serif;
direction: rtl;
}
`]
})
export class AppComponent {
hebrewSuggestions = [
'מהו בינה מלאכותית?',
'איך זה עובד?',
'עזרה'
];
onPromptRequest(args: any) {
// Handle Hebrew prompts
}
}---
Complete Configuration Example
Here's a comprehensive example combining all configuration options:
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewModule, AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
import { L10n } from '@syncfusion/ej2-base';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div class="config-panel">
<button (click)="toggleRtl()">Toggle RTL</button>
<button (click)="togglePersistence()">Toggle Persistence</button>
<button (click)="toggleHeader()">Toggle Header</button>
</div>
<div ejs-aiassistview
#aiAssistViewComponent
id='configuredAssistView'
[height]="'600px'"
[width]="'100%'"
[locale]="currentLocale"
[enableRtl]="isRtlEnabled"
[enablePersistence]="isPersistenceEnabled"
[showHeader]="isHeaderVisible"
[cssClass]="'custom-ai-theme'"
[htmlAttributes]="customAttrs"
[promptPlaceholder]="'Ask me anything...'"
[showClearButton]="true"
[enableScrollToBottom]="true"
(promptRequest)="onPromptRequest($event)">
</div>
`,
styles: [`
.config-panel {
padding: 16px;
display: flex;
gap: 8px;
border-bottom: 1px solid #e0e0e0;
}
:host ::ng-deep .custom-ai-theme {
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
`]
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
currentLocale = 'en-US';
isRtlEnabled = false;
isPersistenceEnabled = true;
isHeaderVisible = true;
customAttrs = {
'aria-label': 'AI Assistant Interface',
'data-version': '2.0'
};
toggleRtl() {
this.isRtlEnabled = !this.isRtlEnabled;
this.currentLocale = this.isRtlEnabled ? 'ar-SA' : 'en-US';
}
togglePersistence() {
this.isPersistenceEnabled = !this.isPersistenceEnabled;
}
toggleHeader() {
this.isHeaderVisible = !this.isHeaderVisible;
}
onPromptRequest(args: any) {
setTimeout(() => {
this.aiAssistViewComponent.addPromptResponse('Response...');
}, 1000);
}
}Custom Views and View Management
Table of Contents
- Adding Custom Views
- Setting View Names
- Active View Management
- Multiple Views Architecture
- View Switching and Management
- Context-Specific Views
- Best Practices
---
Adding Custom Views
The e-views selector enables you to define a collection of different view models within the AI AssistView component. Each view can be independently customized with different appearances and content.
View Types
The AI AssistView supports two view types:
- Assist: Standard conversation view for AI interactions
- Custom: Custom content view for personalized experiences
Basic View Configuration
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewModule, AIAssistViewComponent, PromptRequestEventArgs } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
(promptRequest)="onPromptRequest($event)">
<e-views>
<e-view [type]="'Assist'"></e-view>
<e-view [type]="'Custom'"></e-view>
</e-views>
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
onPromptRequest(args: PromptRequestEventArgs) {
setTimeout(() => {
const response = 'For real-time prompt processing, connect the AIAssistView component to your preferred AI service, such as OpenAI or Azure Cognitive Services.';
this.aiAssistViewComponent.addPromptResponse(response);
}, 1000);
}
}---
Setting View Names
The name property specifies the header name of each view. This text appears as a tab or label identifying the view.
Named Views Example
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewModule, AIAssistViewComponent, PromptRequestEventArgs } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [FormsModule, ReactiveFormsModule, AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
(promptRequest)="onPromptRequest($event)">
<e-views>
<e-view
[type]="'Assist'"
[name]="'Chat Assistant'">
</e-view>
<e-view
[type]="'Custom'"
[name]="'Custom Dashboard'">
</e-view>
</e-views>
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
onPromptRequest(args: PromptRequestEventArgs) {
setTimeout(() => {
const response = 'Response from AI service...';
this.aiAssistViewComponent.addPromptResponse(response);
}, 1000);
}
}---
Active View Management
The activeView property allows you to programmatically control which view is currently displayed in the AI AssistView component. This property uses a zero-based index to identify views.
Basic activeView Usage
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewModule, AIAssistViewComponent, PromptRequestEventArgs } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div class="container">
<div class="controls">
<button (click)="setActiveView(0)">Chat View</button>
<button (click)="setActiveView(1)">Analytics View</button>
<button (click)="setActiveView(2)">Settings View</button>
<div class="current-view">Current View: {{ getCurrentViewName() }}</div>
</div>
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
[activeView]="currentActiveView"
(promptRequest)="onPromptRequest($event)">
<e-views>
<e-view [type]="'Assist'" [name]="'Chat'"></e-view>
<e-view [type]="'Custom'" [name]="'Analytics'"></e-view>
<e-view [type]="'Custom'" [name]="'Settings'"></e-view>
</e-views>
</div>
</div>
`,
styles: [`
.container {
display: flex;
flex-direction: column;
height: 100vh;
}
.controls {
padding: 16px;
border-bottom: 1px solid #e0e0e0;
display: flex;
gap: 8px;
align-items: center;
}
button {
padding: 8px 16px;
border: 1px solid #2196F3;
border-radius: 4px;
cursor: pointer;
background: white;
color: #2196F3;
transition: all 0.2s;
}
button:hover {
background: #2196F3;
color: white;
}
.current-view {
margin-left: auto;
font-weight: 500;
color: #666;
}
`]
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
currentActiveView = 0; // Default to first view
viewNames = ['Chat', 'Analytics', 'Settings'];
setActiveView(index: number) {
this.currentActiveView = index;
console.log(`Switched to view: ${this.viewNames[index]}`);
}
getCurrentViewName(): string {
return this.viewNames[this.currentActiveView] || 'Unknown';
}
onPromptRequest(args: PromptRequestEventArgs) {
// Handle based on active view
console.log(`Processing prompt in ${this.getCurrentViewName()} view`);
setTimeout(() => {
const response = `Response from ${this.getCurrentViewName()} view`;
this.aiAssistViewComponent.addPromptResponse(response);
}, 1000);
}
}Dynamic View Switching Based on User Action
import { Component, ViewChild, OnInit } from '@angular/core';
import { AIAssistViewModule, AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
[activeView]="activeViewIndex"
(promptRequest)="onPromptRequest($event)">
<e-views>
<e-view [type]="'Assist'" [name]="'General Chat'"></e-view>
<e-view [type]="'Assist'" [name]="'Technical Support'"></e-view>
<e-view [type]="'Custom'" [name]="'Dashboard'"></e-view>
</e-views>
</div>
`
})
export class AppComponent implements OnInit {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
activeViewIndex = 0;
ngOnInit() {
// Set initial view based on user role or context
const userRole = this.getUserRole();
if (userRole === 'admin') {
this.activeViewIndex = 2; // Dashboard view
} else if (userRole === 'technical') {
this.activeViewIndex = 1; // Technical support view
} else {
this.activeViewIndex = 0; // General chat view
}
}
getUserRole(): string {
// Get from authentication service
return 'admin'; // Example
}
onPromptRequest(args: any) {
setTimeout(() => {
this.aiAssistViewComponent.addPromptResponse('Response...');
}, 1000);
}
}Conditional View Navigation
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewModule, AIAssistViewComponent, PromptRequestEventArgs } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
[activeView]="activeViewIndex"
(promptRequest)="onPromptRequest($event)">
<e-views>
<e-view [type]="'Assist'" [name]="'Chat'"></e-view>
<e-view [type]="'Custom'" [name]="'Results'"></e-view>
<e-view [type]="'Custom'" [name]="'Error'"></e-view>
</e-views>
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
activeViewIndex = 0;
onPromptRequest(args: PromptRequestEventArgs) {
this.processPrompt(args.prompt).then(
(response) => {
// Success: Switch to results view
this.activeViewIndex = 1;
this.aiAssistViewComponent.addPromptResponse(response);
},
(error) => {
// Error: Switch to error view
this.activeViewIndex = 2;
this.aiAssistViewComponent.addPromptResponse(`Error: ${error.message}`);
}
);
}
private async processPrompt(prompt: string): Promise<string> {
// Simulate API call
return new Promise((resolve, reject) => {
setTimeout(() => {
if (prompt.length > 0) {
resolve(`Processed: ${prompt}`);
} else {
reject(new Error('Empty prompt'));
}
}, 1000);
});
}
}View History and Navigation
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewModule, AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div class="container">
<div class="navigation">
<button (click)="goBack()" [disabled]="!canGoBack()">
← Back
</button>
<button (click)="goForward()" [disabled]="!canGoForward()">
Forward →
</button>
<span class="breadcrumb">{{ getBreadcrumb() }}</span>
</div>
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
[activeView]="activeViewIndex"
(promptRequest)="onPromptRequest($event)">
<e-views>
<e-view [type]="'Assist'" [name]="'Home'"></e-view>
<e-view [type]="'Custom'" [name]="'Search Results'"></e-view>
<e-view [type]="'Custom'" [name]="'Details'"></e-view>
</e-views>
</div>
</div>
`,
styles: [`
.navigation {
padding: 12px;
border-bottom: 1px solid #e0e0e0;
display: flex;
gap: 8px;
align-items: center;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.breadcrumb {
margin-left: 16px;
color: #666;
font-size: 14px;
}
`]
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
activeViewIndex = 0;
viewHistory: number[] = [0];
historyIndex = 0;
viewNames = ['Home', 'Search Results', 'Details'];
navigateToView(viewIndex: number) {
// Add to history
this.historyIndex++;
this.viewHistory = this.viewHistory.slice(0, this.historyIndex);
this.viewHistory.push(viewIndex);
this.activeViewIndex = viewIndex;
}
goBack() {
if (this.canGoBack()) {
this.historyIndex--;
this.activeViewIndex = this.viewHistory[this.historyIndex];
}
}
goForward() {
if (this.canGoForward()) {
this.historyIndex++;
this.activeViewIndex = this.viewHistory[this.historyIndex];
}
}
canGoBack(): boolean {
return this.historyIndex > 0;
}
canGoForward(): boolean {
return this.historyIndex < this.viewHistory.length - 1;
}
getBreadcrumb(): string {
return this.viewNames[this.activeViewIndex];
}
onPromptRequest(args: any) {
// Navigate based on prompt
if (args.prompt.toLowerCase().includes('search')) {
this.navigateToView(1); // Go to search results
} else if (args.prompt.toLowerCase().includes('details')) {
this.navigateToView(2); // Go to details
}
setTimeout(() => {
this.aiAssistViewComponent.addPromptResponse('Response...');
}, 1000);
}
}Workflow-Based View Switching
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewModule, AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
interface WorkflowStep {
viewIndex: number;
name: string;
completed: boolean;
}
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div class="container">
<div class="workflow-stepper">
<div *ngFor="let step of workflowSteps; let i = index"
class="step"
[class.active]="i === activeViewIndex"
[class.completed]="step.completed"
(click)="goToStep(i)">
<span class="step-number">{{ i + 1 }}</span>
<span class="step-name">{{ step.name }}</span>
</div>
</div>
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
[activeView]="activeViewIndex"
(promptRequest)="onPromptRequest($event)">
<e-views>
<e-view [type]="'Assist'" [name]="'Information Gathering'"></e-view>
<e-view [type]="'Custom'" [name]="'Processing'"></e-view>
<e-view [type]="'Custom'" [name]="'Review'"></e-view>
<e-view [type]="'Custom'" [name]="'Complete'"></e-view>
</e-views>
</div>
<div class="workflow-actions">
<button (click)="previousStep()" [disabled]="activeViewIndex === 0">
Previous
</button>
<button (click)="nextStep()" [disabled]="activeViewIndex === workflowSteps.length - 1">
Next
</button>
</div>
</div>
`,
styles: [`
.workflow-stepper {
display: flex;
padding: 20px;
background: #f5f5f5;
border-bottom: 1px solid #e0e0e0;
}
.step {
flex: 1;
display: flex;
align-items: center;
gap: 8px;
padding: 12px;
cursor: pointer;
border-radius: 4px;
transition: all 0.2s;
}
.step.active {
background: #2196F3;
color: white;
}
.step.completed {
color: #4CAF50;
}
.step-number {
width: 28px;
height: 28px;
border-radius: 50%;
background: rgba(0,0,0,0.1);
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
}
.workflow-actions {
padding: 16px;
border-top: 1px solid #e0e0e0;
display: flex;
justify-content: space-between;
}
`]
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
activeViewIndex = 0;
workflowSteps: WorkflowStep[] = [
{ viewIndex: 0, name: 'Information', completed: false },
{ viewIndex: 1, name: 'Processing', completed: false },
{ viewIndex: 2, name: 'Review', completed: false },
{ viewIndex: 3, name: 'Complete', completed: false }
];
goToStep(stepIndex: number) {
// Only allow going to completed steps or the next step
if (stepIndex <= this.activeViewIndex + 1 || this.workflowSteps[stepIndex].completed) {
this.activeViewIndex = stepIndex;
}
}
nextStep() {
if (this.activeViewIndex < this.workflowSteps.length - 1) {
this.workflowSteps[this.activeViewIndex].completed = true;
this.activeViewIndex++;
}
}
previousStep() {
if (this.activeViewIndex > 0) {
this.activeViewIndex--;
}
}
onPromptRequest(args: any) {
setTimeout(() => {
this.aiAssistViewComponent.addPromptResponse('Step completed!');
// Auto-advance to next step after response
if (this.activeViewIndex < this.workflowSteps.length - 1) {
setTimeout(() => {
this.nextStep();
}, 1500);
}
}, 1000);
}
}Reading Current Active View
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { AIAssistViewModule, AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
[activeView]="activeViewIndex"
(promptRequest)="onPromptRequest($event)">
<e-views>
<e-view [type]="'Assist'" [name]="'Chat'"></e-view>
<e-view [type]="'Custom'" [name]="'Analytics'"></e-view>
</e-views>
</div>
`
})
export class AppComponent implements AfterViewInit {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
activeViewIndex = 0;
ngAfterViewInit() {
// Access the current active view
console.log('Current active view:', this.aiAssistViewComponent.activeView);
// Track view changes
this.trackViewChanges();
}
trackViewChanges() {
// Monitor activeViewIndex changes
let previousView = this.activeViewIndex;
setInterval(() => {
if (this.activeViewIndex !== previousView) {
console.log(`View changed from ${previousView} to ${this.activeViewIndex}`);
this.onViewChange(previousView, this.activeViewIndex);
previousView = this.activeViewIndex;
}
}, 100);
}
onViewChange(fromView: number, toView: number) {
// Custom logic when view changes
console.log('View transition:', { from: fromView, to: toView });
// Clear state, load data, etc.
this.loadViewData(toView);
}
loadViewData(viewIndex: number) {
// Load data specific to the view
console.log(`Loading data for view ${viewIndex}`);
}
onPromptRequest(args: any) {
setTimeout(() => {
this.aiAssistViewComponent.addPromptResponse('Response...');
}, 1000);
}
}---
Multiple Views Architecture
Three-View Setup
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
(promptRequest)="onPromptRequest($event)">
<e-views>
<e-view
[type]="'Assist'"
[name]="'AI Assistant'">
</e-view>
<e-view
[type]="'Custom'"
[name]="'Analytics'">
</e-view>
<e-view
[type]="'Custom'"
[name]="'Settings'">
</e-view>
</e-views>
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
onPromptRequest(args: PromptRequestEventArgs) {
// Handle prompts for assist view
this.processAIRequest(args);
}
processAIRequest(args: PromptRequestEventArgs) {
setTimeout(() => {
const response = 'Processed prompt response...';
this.aiAssistViewComponent.addPromptResponse(response);
}, 1000);
}
}---
View Switching and Management
Legacy View Switching (Alternative Approach)
If you need alternative view switching approaches, you can use custom state management:
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewModule, AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div class="container">
<div class="controls">
<button (click)="switchView('assist')">AI Chat</button>
<button (click)="switchView('analytics')">Analytics</button>
<button (click)="switchView('settings')">Settings</button>
</div>
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
[activeView]="selectedViewIndex"
(promptRequest)="onPromptRequest($event)">
<e-views>
<e-view [type]="'Assist'" [name]="'AI Chat'"></e-view>
<e-view [type]="'Custom'" [name]="'Analytics'"></e-view>
<e-view [type]="'Custom'" [name]="'Settings'"></e-view>
</e-views>
</div>
</div>
`,
styles: [`
.container {
display: flex;
flex-direction: column;
height: 100vh;
}
.controls {
padding: 16px;
border-bottom: 1px solid #e0e0e0;
display: flex;
gap: 8px;
}
button {
padding: 8px 16px;
border: 1px solid #ccc;
border-radius: 4px;
cursor: pointer;
background: #f5f5f5;
transition: all 0.2s;
}
button:hover {
background: #e0e0e0;
}
`]
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
selectedViewIndex = 0;
switchView(viewName: string) {
const viewMap: { [key: string]: number } = {
'assist': 0,
'analytics': 1,
'settings': 2
};
this.selectedViewIndex = viewMap[viewName];
}
onPromptRequest(args: any) {
setTimeout(() => {
const response = 'Response for current view...';
this.aiAssistViewComponent.addPromptResponse(response);
}, 1000);
}
}---
Context-Specific Views
Role-Based View Configuration
interface ViewConfig {
name: string;
type: 'Assist' | 'Custom';
prompts?: Array<{ prompt: string; response: string }>;
}
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
(promptRequest)="onPromptRequest($event)">
<e-views>
<e-view
*ngFor="let view of views"
[type]="view.type"
[name]="view.name"
[prompts]="view.prompts">
</e-view>
</e-views>
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
views: ViewConfig[] = [
{
name: 'General',
type: 'Assist',
prompts: []
},
{
name: 'Technical',
type: 'Assist',
prompts: []
},
{
name: 'History',
type: 'Custom',
prompts: [
{
prompt: 'Previous conversation 1',
response: 'Response 1'
}
]
}
];
onPromptRequest(args: any) {
// Handle request based on current view
this.processContextualRequest();
}
processContextualRequest() {
const currentViewIndex = (this.aiAssistViewComponent as any).selectedViewIndex;
const currentView = this.views[currentViewIndex];
// Process based on view type
if (currentView.type === 'Assist') {
this.handleAssistRequest();
} else {
this.handleCustomRequest();
}
}
handleAssistRequest() {
setTimeout(() => {
const response = 'Assist view response...';
this.aiAssistViewComponent.addPromptResponse(response);
}, 1000);
}
handleCustomRequest() {
setTimeout(() => {
const response = 'Custom view response...';
this.aiAssistViewComponent.addPromptResponse(response);
}, 1000);
}
}---
Best Practices for Multiple Views
1. Clear Purpose for Each View
- Assist View: For conversational AI interactions
- Custom View 1: For analytics or reporting
- Custom View 2: For settings or configuration
2. Independent State Management
// Each view can maintain its own state
viewStates = {
'assist': { history: [], settings: {} },
'analytics': { data: [], filters: {} },
'settings': { preferences: {} }
};3. Context-Aware Processing
onPromptRequest(args: any) {
const currentViewName = this.getCurrentViewName();
if (currentViewName === 'assist') {
this.processAIQuery(args);
} else if (currentViewName === 'analytics') {
this.processAnalyticsQuery(args);
}
}4. Consistent Styling Across Views
template: `
<div ejs-aiassistview
id='aiAssistView'
[cssClass]="'unified-theme'">
<e-views>
<e-view [type]="'Assist'" [name]="'Chat'"></e-view>
<e-view [type]="'Custom'" [name]="'Analytics'"></e-view>
</e-views>
</div>
`
styles: [`
:host ::ng-deep .unified-theme {
/* Styles apply to all views */
}
`]---
Use Cases
1. Customer Support Portal: Separate views for support chat, FAQ, and settings 2. Data Analysis Tool: One view for queries, another for results visualization 3. Educational Platform: Chat for tutoring, custom view for progress tracking 4. Enterprise Applications: Different views for different departments or functions
Event Handling and User Interactions
Table of Contents
- Component Lifecycle Events
- User Input Events
- File Upload Events
- Event Arguments Reference
- Event Handling Patterns
---
Component Lifecycle Events
Created Event
The created event is triggered when the AI AssistView component rendering is completed. This is useful for initialization logic and accessing component instance.
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [ AIAssistViewModule ],
standalone: true,
selector: 'app-root',
// specifies the template string for the AI AssistView component
template: `<div ejs-aiassistview #aiAssistViewComponent (created)="onCreated()"></div>`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
public onCreated = () => {
// Your required action here
};
}---
User Input Events
PromptRequest Event
The promptRequest event is triggered when a user sends a prompt request in the AI AssistView component. This is where you handle user queries and generate responses.
Event Arguments: PromptRequestEventArgs
import { AIAssistViewModule, PromptRequestEventArgs } from '@syncfusion/ej2-angular-interactive-chat';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [ AIAssistViewModule ],
standalone: true,
selector: 'app-root',
template: `<div ejs-aiassistview #aiAssistViewComponent (promptRequest)="onPromptRequest($event)"></div>`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
public onPromptRequest = (args: PromptRequestEventArgs) => {
console.log('Prompt:', args.prompt);
console.log('Attached files:', args.attachedFiles);
console.log('Prompt suggestions:', args.promptSuggestions);
// Cancel the request if needed
if (args.prompt.length < 3) {
args.cancel = true;
alert('Please enter at least 3 characters');
return;
}
// Process the prompt
**Event Arguments:** `PromptChangedEventArgs`
import { AIAssistViewModule, PromptChangedEventArgs } from '@syncfusion/ej2-angular-interactive-chat'; import { Component, ViewChild } from '@angular/core'; import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({ imports: [ AIAssistViewModule ], standalone: true, selector: 'app-root', template: <div ejs-aiassistview #aiAssistViewComponent (promptChanged)="onPromptChanged($event)"></div> })
export class AppComponent { @ViewChild('aiAssistViewComponent') public aiAssistViewComponent!: AIAssistViewComponent;
public onPromptChanged = (args: PromptChangedEventArgs) => { console.log('Current value:', args.value); console.log('Previous value:', args.previousValue);
// Real-time validation if (args.value.length > 1000) { alert('Prompt is too long. Maximum 1000 characters allowed.'); }
// Auto-suggestions based on input if (args.value.startsWith('/')) { this.showCommandSuggestions(args.value); } };
private showCommandSuggestions(value: string) { // Show command suggestions } }
**Available Properties in PromptChangedEventArgs:**
- `value` (string) - Current value of the prompt
- `previousValue` (string) - Previous value before the change
- `element` (HTMLElement) - HTML element of the text area container
- `event` (Event) - Underlying DOM event
- `name` (string) - Event nameort { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [ AIAssistViewModule ],
standalone: true,
selector: 'app-root',
// specifies the template string for the AI AssistView component
template: `<div ejs-aiassistview #aiAssistViewComponent (promptChanged)="onPromptChanged()"></div>`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
public onPromptChanged = () => {
// Your required action here
};
}---
File Upload Events
BeforeAttachmentUpload Event
The beforeAttachmentUpload event is triggered before attached files begin uploading. Use this for validation of file type, size, or canceling the upload.
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
import { UploadingEventArgs } from '@syncfusion/ej2-inputs';
@Component({
imports: [ AIAssistViewModule ],
standalone: true,
selector: 'app-root',
// specifies the template string for the AI AssistView component
template: `<div ejs-aiassistview #aiAssistViewComponent [enableAttachments]="enableAttachments" [attachmentSettings]="attachmentSettings" (promptRequest)="onPromptRequest()" (beforeAttachmentUpload)="onBeforeAttachmentUpload($event)" ></div>`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
public onBeforeAttachmentUpload = (args: UploadingEventArgs) => {
// Your required action here
};
public onPromptRequest = () => {
setTimeout(() => {
let defaultResponse = 'For real-time prompt processing, connect the AIAssistView component to your preferred AI service, such as OpenAI or Azure Cognitive Services. Ensure you obtain the necessary API credentials to authenticate and enable seamless integration.';
this.aiAssistViewComponent.addPromptResponse(defaultResponse);
}, 1000);
};
public enableAttachments: boolean = true;
public attachmentSettings = {
saveUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Save',
removeUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Remove'
};
}AttachmentUploadSuccess Event
The attachmentUploadSuccess event is triggered when an attached file is successfully uploaded. Use this for post-upload processing or confirmation.
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
import { UploadingEventArgs } from '@syncfusion/ej2-inputs';
@Component({
imports: [ AIAssistViewModule ],
standalone: true,
selector: 'app-root',
// specifies the template string for the AI AssistView component
template: `<div ejs-aiassistview #aiAssistViewComponent [enableAttachments]="enableAttachments" [attachmentSettings]="attachmentSettings" (promptRequest)="onPromptRequest()" (attachmentUploadSuccess)="onAttachmentUploadSuccess($event)" ></div>`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
public onAttachmentUploadSuccess = (args: UploadingEventArgs) => {
// Your required action here
};
public onPromptRequest = () => {
setTimeout(() => {
let defaultResponse = 'For real-time prompt processing, connect the AIAssistView component to your preferred AI service, such as OpenAI or Azure Cognitive Services. Ensure you obtain the necessary API credentials to authenticate and enable seamless integration.';
this.aiAssistViewComponent.addPromptResponse(defaultResponse);
}, 1000);
};
public enableAttachments: boolean = true;
public attachmentSettings = {
saveUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Save',
removeUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Remove'
};
}---
Additional Events
AttachmentUploadFailure Event
The attachmentUploadFailure event is triggered when an attached file upload fails in the AI AssistView.
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
import { UploadingEventArgs } from '@syncfusion/ej2-inputs';
@Component({
imports: [ AIAssistViewModule ],
standalone: true,
selector: 'app-root',
// specifies the template string for the AI AssistView component
template: `<div ejs-aiassistview #aiAssistViewComponent [enableAttachments]="enableAttachments" [attachmentSettings]="attachmentSettings" (promptRequest)="onPromptRequest()" (created)="onCreated()" (attachmentUploadFailure)="onAttachmentUploadFailure($event)" ></div>`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
public onAttachmentUploadFailure = (args: UploadingEventArgs) => {
// Your required action here
};
public onPromptRequest = () => {
setTimeout(() => {
let defaultResponse = 'For real-time prompt processing, connect the AIAssistView component to your preferred AI service, such as OpenAI or Azure Cognitive Services. Ensure you obtain the necessary API credentials to authenticate and enable seamless integration.';
this.aiAssistViewComponent.addPromptResponse(defaultResponse);
}, 1000);
};
public enableAttachments: boolean = true;
public attachmentSettings = {
saveUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Save',
removeUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Remove'
};
public onCreated = () => {
// Your required action here
};
}AttachmentRemoved Event
The attachmentRemoved event is triggered when an attached file is removed from the AI AssistView.
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
import { UploadingEventArgs } from '@syncfusion/ej2-inputs';
@Component({
imports: [ AIAssistViewModule ],
standalone: true,
selector: 'app-root',
// specifies the template string for the AI AssistView component
template: `<div ejs-aiassistview #aiAssistViewComponent [enableAttachments]="enableAttachments" [attachmentSettings]="attachmentSettings" (promptRequest)="onPromptRequest()" (attachmentRemoved)="onAttachmentRemoved($event)" ></div>`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
public onAttachmentRemoved = (args: UploadingEventArgs) => {
// Your required action here
};
public onPromptRequest = () => {
setTimeout(() => {
let defaultResponse = 'For real-time prompt processing, connect the AIAssistView component to your preferred AI service, such as OpenAI or Azure Cognitive Services. Ensure you obtain the necessary API credentials to authenticate and enable seamless integration.';
this.aiAssistViewComponent.addPromptResponse(defaultResponse);
}, 1000);
};
public enableAttachments: boolean = true;
public attachmentSettings = {
saveUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Save',
removeUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Remove'
};
}---
Event Arguments Reference
This section provides detailed information about all event argument interfaces used in the AI AssistView component.
PromptRequestEventArgs
Provides information when a prompt request is made.
Properties:
| Property | Type | Description |
|---|---|---|
prompt | string | The text of the prompt request sent by the user |
attachedFiles | FileInfo[] | Array of files attached with the prompt request |
promptSuggestions | string[] | List of prompt suggestions to assist the user |
responseToolbarItems | ToolbarItemModel[] | Toolbar items displayed alongside the response view |
cancel | boolean | Set to true to cancel the prompt request |
name | string | Name of the event |
Example Usage:
public onPromptRequest = (args: PromptRequestEventArgs) => {
// Access prompt text
console.log('User prompt:', args.prompt);
// Check for attached files
if (args.attachedFiles && args.attachedFiles.length > 0) {
console.log('Files attached:', args.attachedFiles.length);
args.attachedFiles.forEach(file => {
console.log('File:', file.name, file.size);
});
}
// Cancel if prompt is too short
if (args.prompt.trim().length < 5) {
args.cancel = true;
alert('Please enter at least 5 characters');
return;
}
// Add custom response toolbar items
args.responseToolbarItems = [
{ type: 'Button', iconCss: 'e-icons e-copy', tooltip: 'Copy response' },
{ type: 'Button', iconCss: 'e-icons e-refresh', tooltip: 'Regenerate' }
];
// Process the prompt
this.callAIService(args.prompt, args.attachedFiles);
};---
PromptChangedEventArgs
Provides information when the prompt text changes.
Properties:
| Property | Type | Description |
|---|---|---|
value | string | Current value of the prompt after the change |
previousValue | string | Previous value of the prompt before the change |
element | HTMLElement | HTML element of the text area container |
event | Event | Underlying DOM event that triggered the change |
name | string | Name of the event |
Example Usage:
public onPromptChanged = (args: PromptChangedEventArgs) => {
// Track changes
console.log('Changed from:', args.previousValue);
console.log('Changed to:', args.value);
// Character count validation
const maxLength = 1000;
if (args.value.length > maxLength) {
alert(`Prompt exceeds maximum length of ${maxLength} characters`);
}
// Show character counter
this.characterCount = args.value.length;
// Auto-save draft
if (args.value.length > 10) {
this.saveDraft(args.value);
}
// Command detection
if (args.value.startsWith('/')) {
this.showCommandPalette(args.value);
}
// Direct element manipulation if needed
if (args.element) {
console.log('Text area element:', args.element);
}
};---
StopRespondingEventArgs
Provides information when the 'Stop Responding' button is clicked during an ongoing response.
Properties:
| Property | Type | Description |
|---|---|---|
prompt | string | The prompt text associated with the request |
dataIndex | number | Index of the prompt in the prompt list |
event | Event | Underlying DOM event that triggered the action |
name | string | Name of the event |
Example Usage:
import { AIAssistViewModule, StopRespondingEventArgs } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [ AIAssistViewModule ],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
(stopRespondingClick)="onStopResponding($event)">
</div>
`
})
export class AppComponent {
private abortController: AbortController | null = null;
public onStopResponding = (args: StopRespondingEventArgs) => {
console.log('Stopping response for prompt:', args.prompt);
console.log('Data index:', args.dataIndex);
// Abort ongoing API request
if (this.abortController) {
this.abortController.abort();
this.abortController = null;
}
// Update UI to show stopped state
this.showStoppedMessage(args.dataIndex);
// Log the action
this.logStopAction(args.prompt, args.dataIndex);
};
private showStoppedMessage(index: number) {
// Show partial response with indicator that it was stopped
this.aiAssistViewComponent.addPromptResponse(
'Response generation stopped by user.',
index
);
}
private logStopAction(prompt: string, index: number) {
console.log(`User stopped response at index ${index} for prompt: "${prompt}"`);
}
}---
AttachmentClickEventArgs
Provides information when an attached file is clicked.
Properties:
| Property | Type | Description |
|---|---|---|
file | FileInfo | Information about the clicked file |
event | Event | Underlying DOM event |
cancel | boolean | Set to true to cancel the default click action |
name | string | Name of the event |
Example Usage:
import { AttachmentClickEventArgs } from '@syncfusion/ej2-angular-interactive-chat';
public onAttachmentClick = (args: AttachmentClickEventArgs) => {
console.log('File clicked:', args.file.name);
// Custom preview logic
if (args.file.type.startsWith('image/')) {
this.showImagePreview(args.file);
args.cancel = true; // Prevent default action
}
// Download logic
if (args.file.size > 10 * 1024 * 1024) { // 10MB
if (!confirm('This file is large. Do you want to download it?')) {
args.cancel = true;
}
}
};---
FileInfo Interface
Represents information about an attached file.
Properties:
| Property | Type | Description |
|---|---|---|
name | string | Name of the file |
size | number | Size of the file in bytes |
type | string | MIME type of the file |
rawFile | File | Raw File object from the browser |
---
Complete Event Handling Example
Here's a comprehensive example using all major event arguments:
import { Component, ViewChild } from '@angular/core';
import {
AIAssistViewModule,
AIAssistViewComponent,
PromptRequestEventArgs,
PromptChangedEventArgs,
StopRespondingEventArgs,
AttachmentClickEventArgs
} from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div class="event-info" *ngIf="lastEvent">
<strong>Last Event:</strong> {{ lastEvent }}
</div>
<div ejs-aiassistview
#aiAssistViewComponent
[enableAttachments]="true"
[attachmentSettings]="attachmentSettings"
(promptRequest)="onPromptRequest($event)"
(promptChanged)="onPromptChanged($event)"
(stopRespondingClick)="onStopResponding($event)">
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
lastEvent = '';
characterCount = 0;
private abortController: AbortController | null = null;
public attachmentSettings = {
saveUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Save',
removeUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Remove',
attachmentClick: this.onAttachmentClick.bind(this)
};
public onPromptRequest = (args: PromptRequestEventArgs) => {
this.lastEvent = `promptRequest: "${args.prompt}"`;
// Validation
if (args.prompt.trim().length < 3) {
args.cancel = true;
alert('Prompt must be at least 3 characters');
return;
}
// Handle attached files
if (args.attachedFiles?.length > 0) {
console.log(`Processing ${args.attachedFiles.length} files`);
}
// Create abort controller for cancellation
this.abortController = new AbortController();
// Call AI service
this.processPrompt(args.prompt, this.abortController.signal);
};
public onPromptChanged = (args: PromptChangedEventArgs) => {
this.lastEvent = `promptChanged: ${args.value.length} chars`;
this.characterCount = args.value.length;
// Validation feedback
if (args.value.length > 1000) {
console.warn('Prompt is getting long');
}
};
public onStopResponding = (args: StopRespondingEventArgs) => {
this.lastEvent = `stopResponding: index ${args.dataIndex}`;
// Abort ongoing request
if (this.abortController) {
this.abortController.abort();
this.abortController = null;
}
// Update UI
this.aiAssistViewComponent.addPromptResponse(
'Response stopped by user.',
args.dataIndex
);
};
public onAttachmentClick = (args: AttachmentClickEventArgs) => {
this.lastEvent = `attachmentClick: ${args.file.name}`;
// Custom file handling
if (args.file.type.startsWith('image/')) {
this.showImagePreview(args.file);
args.cancel = true;
}
};
private async processPrompt(prompt: string, signal: AbortSignal) {
try {
// Simulate AI processing
await new Promise((resolve, reject) => {
const timeout = setTimeout(resolve, 2000);
signal.addEventListener('abort', () => {
clearTimeout(timeout);
reject(new Error('Aborted'));
});
});
if (!signal.aborted) {
this.aiAssistViewComponent.addPromptResponse(`Response to: ${prompt}`);
}
} catch (error: any) {
if (error.message !== 'Aborted') {
console.error('Error processing prompt:', error);
}
}
}
private showImagePreview(file: FileInfo) {
// Image preview logic
console.log('Showing preview for:', file.name);
}
}---
AttachmentClick Event
The attachmentClick event is triggered when an attached file is clicked in the AI AssistView.
import { AIAssistViewModule, AttachmentClickEventArgs } from '@syncfusion/ej2-angular-interactive-chat';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [ AIAssistViewModule ],
standalone: true,
selector: 'app-root',
// specifies the template string for the AI AssistView component
template: `<div ejs-aiassistview #aiAssistViewComponent [enableAttachments]="enableAttachments" [attachmentSettings]="attachmentSettings" (promptRequest)="onPromptRequest()" (created)="onCreated()" ></div>`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
public onAttachmentClick = (args: AttachmentClickEventArgs) => {
// Your required action here
};
public onPromptRequest = () => {
setTimeout(() => {
let defaultResponse = 'For real-time prompt processing, connect the AIAssistView component to your preferred AI service, such as OpenAI or Azure Cognitive Services. Ensure you obtain the necessary API credentials to authenticate and enable seamless integration.';
this.aiAssistViewComponent.addPromptResponse(defaultResponse);
}, 1000);
};
public enableAttachments: boolean = true;
public attachmentSettings = {
saveUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Save',
removeUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Remove',
attachmentClick: this.onAttachmentClick
};
public onCreated = () => {
// Your required action here
};
}Event Handling Best Practices
1. Always validate event data
- Check if files exist before processing in attachment events
- Validate prompt content before processing in promptRequest events
- Handle null or undefined values gracefully
2. Implement proper error handling
- Use try-catch blocks in event handlers
- Provide user feedback when errors occur
- Log errors for debugging purposes
3. Use arrow functions for event handlers
- Maintains proper
thiscontext in Angular components - Ensures component methods can access component properties
- Recommended pattern for Syncfusion event handlers
4. Handle asynchronous operations
- Use async/await for cleaner code
- Always catch promise rejections
- Consider timeout handling for long-running operations
5. Manage file uploads properly
- Validate file types and sizes before upload
- Implement proper error handling for failed uploads
- Track upload progress for better UX
Common Event Patterns
Pattern 1: Validated Prompt Processing
public onPromptRequest = () => {
// Your required action here
setTimeout(() => {
let defaultResponse = 'For real-time prompt processing, connect the AIAssistView component to your preferred AI service, such as OpenAI or Azure Cognitive Services. Ensure you obtain the necessary API credentials to authenticate and enable seamless integration.';
this.aiAssistViewComponent.addPromptResponse(defaultResponse);
}, 1000);
};Pattern 2: File Upload Validation
public onBeforeAttachmentUpload = (args: UploadingEventArgs) => {
// Your required action here
};Pattern 3: Post-Upload Processing
public onAttachmentUploadSuccess = (args: UploadingEventArgs) => {
// Your required action here
};File Attachments in Angular AI AssistView Component
The AI AssistView component supports file attachments, allowing users to include files along with their prompts to provide additional context and enhance interactions. Users can upload documents, images, and other file types to supplement their queries. Enable this functionality using the enableAttachments property and customize the behavior through the attachmentSettings configuration.
Enable File Attachments
Enable file attachment support by setting the enableAttachments property to true. By default, it is disabled.
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [ AIAssistViewModule ],
standalone: true,
selector: 'app-root',
template: `<div ejs-aiassistview #aiAssistViewComponent [enableAttachments]="enableAttachments" (promptRequest)="onPromptRequest()" ></div>`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
public onPromptRequest = () => {
setTimeout(() => {
let defaultResponse = 'For real-time prompt processing, connect the AIAssistView component to your preferred AI service, such as OpenAI or Azure Cognitive Services. Ensure you obtain the necessary API credentials to authenticate and enable seamless integration.';
this.aiAssistViewComponent.addPromptResponse(defaultResponse);
}, 1000);
};
public enableAttachments: boolean = true;
}---
Configure Attachment Settings
Use the attachmentSettings property to customize file attachment behavior, including upload endpoints, file type restrictions, and size limits.
Setting Save URL and Remove URL
Set the saveUrl and removeUrl properties to specify server endpoints for handling file uploads and removals. The saveUrl processes file uploads, while the removeUrl handles file deletion requests.
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [ AIAssistViewModule ],
standalone: true,
selector: 'app-root',
template: `<div ejs-aiassistview #aiAssistViewComponent [enableAttachments]="enableAttachments" (promptRequest)="onPromptRequest()" [attachmentSettings]="attachmentSettings" ></div>`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
public onPromptRequest = () => {
setTimeout(() => {
let defaultResponse = 'For real-time prompt processing, connect the AIAssistView component to your preferred AI service, such as OpenAI or Azure Cognitive Services. Ensure you obtain the necessary API credentials to authenticate and enable seamless integration.';
this.aiAssistViewComponent.addPromptResponse(defaultResponse);
}, 1000);
};
public enableAttachments: boolean = true;
public attachmentSettings = {
saveUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Save',
removeUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Remove'
};
}Setting File Type
Use the allowedFileTypes property to specify which file types users can upload. This property accepts file extensions (e.g., '.pdf', '.docx') or MIME types to control the types of files that can be attached.
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [ AIAssistViewModule ],
standalone: true,
selector: 'app-root',
template: `<div ejs-aiassistview #aiAssistViewComponent [enableAttachments]="enableAttachments" (promptRequest)="onPromptRequest()" [attachmentSettings]="attachmentSettings" ></div>`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
public onPromptRequest = () => {
setTimeout(() => {
let defaultResponse = 'For real-time prompt processing, connect the AIAssistView component to your preferred AI service, such as OpenAI or Azure Cognitive Services. Ensure you obtain the necessary API credentials to authenticate and enable seamless integration.';
this.aiAssistViewComponent.addPromptResponse(defaultResponse);
}, 1000);
};
public enableAttachments: boolean = true;
public attachmentSettings = {
saveUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Save',
removeUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Remove',
allowedFileTypes: '.png'
};
}Setting File Size
Configure the maxFileSize property to define the maximum file size allowed for uploads. Specify the size in bytes. The default value is 2000000 bytes (2 MB). Files exceeding this limit will not be uploaded.
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [ AIAssistViewModule ],
standalone: true,
selector: 'app-root',
template: `<div ejs-aiassistview #aiAssistViewComponent [enableAttachments]="enableAttachments" (promptRequest)="onPromptRequest()" [attachmentSettings]="attachmentSettings" ></div>`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
public onPromptRequest = () => {
setTimeout(() => {
let defaultResponse = 'For real-time prompt processing, connect the AIAssistView component to your preferred AI service, such as OpenAI or Azure Cognitive Services. Ensure you obtain the necessary API credentials to authenticate and enable seamless integration.';
this.aiAssistViewComponent.addPromptResponse(defaultResponse);
}, 1000);
};
public enableAttachments: boolean = true;
public attachmentSettings = {
saveUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Save',
removeUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Remove',
maxFileSize: 1000000
};
}---
Setting Maximum Count
Restrict how many files can be attached at once using the maximumCount property. The default value is 10. If users select more than the allowed count, the maximum count reached error will be displayed.
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewComponent } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [ AIAssistViewModule ],
standalone: true,
selector: 'app-root',
template: `<div ejs-aiassistview #aiAssistViewComponent [enableAttachments]="enableAttachments" (promptRequest)="onPromptRequest()" [attachmentSettings]="attachmentSettings" ></div>`
})
export class App {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
public onPromptRequest = () => {
setTimeout(() => {
let defaultResponse = 'For real-time prompt processing, connect the AIAssistView component to your preferred AI service, such as OpenAI or Azure Cognitive Services. Ensure you obtain the necessary API credentials to authenticate and enable seamless integration.';
this.aiAssistViewComponent.addPromptResponse(defaultResponse);
}, 1000);
};
public enableAttachments: boolean = true;
public attachmentSettings = {
saveUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Save',
removeUrl: 'https://services.syncfusion.com/js/production/api/FileUploader/Remove',
maxFileSize: 1000000,
maximumCount:5
};
}Getting Started with Syncfusion AI AssistView
Installation and Package Setup
The Syncfusion AI AssistView component is distributed as part of the @syncfusion/ej2-angular-interactive-chat package. It includes all necessary dependencies for creating conversational AI interfaces in Angular.
Required Dependencies
|-- @syncfusion/ej2-angular-interactive-chat
|-- @syncfusion/ej2-angular-base
|-- @syncfusion/ej2-base
|-- @syncfusion/ej2-navigations
|-- @syncfusion/ej2-inputsInstallation Steps
Step 1: Set up Angular environment
Install Angular CLI if you haven't already:
npm install -g @angular/cliStep 2: Create Angular application
ng new my-app
cd my-appStep 3: Install AI AssistView package
For modern Angular (version 12+) with Ivy library distribution:
npm install @syncfusion/ej2-angular-interactive-chat --saveCSS Configuration
Add required CSS imports to your src/styles.css file:
@import "../node_modules/@syncfusion/ej2-base/styles/material3.css";
@import '../node_modules/@syncfusion/ej2-interactive-chat/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-inputs/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-navigations/styles/material3.css';
@import '../node_modules/@syncfusion/ej2-notifications/styles/material3.css';These imports include all themes and styling required for the component to render correctly. You can replace material3 with other available themes like material, bootstrap5, fabric, or tailwind.
Basic Component Implementation
Minimal Example
Update src/app/app.component.ts:
import { Component } from '@angular/core';
import { AIAssistViewModule } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `<div ejs-aiassistview id='aiAssistView'></div>`
})
export class AppComponent { }Bootstrap the Application
Update src/main.ts:
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import 'zone.js';
bootstrapApplication(AppComponent).catch((err) => console.error(err));Run the Application
ng serveVisit http://localhost:4200/ in your browser to see the component.
Initial Configuration Example
Here's a basic setup with suggestions and event handling:
import { Component, ViewChild } from '@angular/core';
import { AIAssistViewModule, AIAssistViewComponent, PromptRequestEventArgs } from '@syncfusion/ej2-angular-interactive-chat';
@Component({
imports: [AIAssistViewModule],
standalone: true,
selector: 'app-root',
template: `
<div ejs-aiassistview
#aiAssistViewComponent
id='aiAssistView'
[promptSuggestions]="suggestions"
(promptRequest)="onPromptRequest($event)"
style="height: 100vh">
</div>
`
})
export class AppComponent {
@ViewChild('aiAssistViewComponent')
public aiAssistViewComponent!: AIAssistViewComponent;
suggestions = [
'What can you help me with?',
'Show me an example',
'Tell me about your features'
];
onPromptRequest(args: PromptRequestEventArgs) {
// Handle the prompt request here
setTimeout(() => {
const response = 'Thank you for your prompt. This is a sample response.';
this.aiAssistViewComponent.addPromptResponse(response);
}, 1000);
}
}Version Compatibility
- Angular Version: 12 and above (with Ivy library package)
- Angular Version: Below 12 (with ngcc package)
- Syncfusion EJ2 Package: Version 20.2.36 and above
Note: Starting from version 33.1x, the component automatically scrolls to the latest prompt and response, eliminating the need for manual scrolling.
Next Steps
- Configure prompt suggestions for your use case
- Set up event handlers for
promptRequest - Choose an AI service provider (OpenAI, Gemini, etc.)
- Customize appearance and styling