@ui18n/angular
Version:
🅰️ Modern Angular internationalization with standalone components, signals, and dependency injection support for Angular 15+
469 lines (373 loc) • 11.3 kB
Markdown
# @ui18n/angular
> Angular集成包 - 为Angular应用提供完整的国际化解决方案
[](https://www.npmjs.com/package/@ui18n/angular)
[](https://www.typescriptlang.org/)
[](https://angular.io/)
## ✨ 特性
- **🎯 Angular原生支持**:完美集成Angular生态系统
- **📦 完整组件库**:服务、指令、管道、组件一应俱全
- **🔄 响应式设计**:基于RxJS的响应式翻译状态管理
- **🎨 可定制UI**:提供默认组件,支持完全自定义
- **⚡ 智能翻译**:继承UI18n核心的智能翻译管道
- **📊 实时监控**:翻译状态、成本、性能实时监控
- **🌍 企业级**:支持大规模Angular应用的国际化需求
## 🚀 快速开始
### 安装
```bash
npm install @ui18n/angular @ui18n/core
```
### 基础配置
```typescript
// app.module.ts
import { NgModule } from '@angular/core';
import { UI18nModule } from '@ui18n/angular';
@NgModule({
imports: [
UI18nModule.forRoot({
config: {
defaultLanguage: 'zh-CN',
aiProvider: {
type: 'openai',
apiKey: 'your-api-key'
}
},
autoInitialize: true
})
]
})
export class AppModule {}
```
### 在组件中使用
```typescript
// app.component.ts
import { Component, OnInit } from '@angular/core';
import { UI18nService } from '@ui18n/angular';
@Component({
selector: 'app-root',
template: `
<!-- 使用指令 -->
<h1 ui18nTranslate="欢迎使用UI18n"></h1>
<!-- 使用管道 -->
<p>{{ '这是一个示例文本' | ui18nTranslate }}</p>
<!-- 语言选择器 -->
<ui18n-language-selector
[showSearch]="true"
(languageChange)="onLanguageChange($event)">
</ui18n-language-selector>
<!-- 翻译状态 -->
<div *ngIf="isLoading$ | async">翻译中...</div>
`
})
export class AppComponent implements OnInit {
isLoading$ = this.ui18nService.isLoading$;
constructor(private ui18nService: UI18nService) {}
async ngOnInit() {
// 如果没有自动初始化,可以手动初始化
if (!this.ui18nService.isInitialized()) {
await this.ui18nService.initialize({
defaultLanguage: 'zh-CN',
aiProvider: {
type: 'openai',
apiKey: 'your-api-key'
}
});
}
}
onLanguageChange(language: string) {
console.log('语言已切换到:', language);
}
}
```
## 📚 API文档
### UI18nService
核心服务,提供所有翻译功能和状态管理。
```typescript
import { UI18nService } from '@ui18n/angular';
export class MyComponent {
constructor(private ui18nService: UI18nService) {}
async translateText() {
// 单个翻译
const result = await this.ui18nService.translate('Hello World', 'zh-CN');
console.log(result.translatedText); // "你好世界"
// 简化翻译
const text = await this.ui18nService.t('Hello World');
// 批量翻译
const results = await this.ui18nService.translateBatch([
'Hello', 'World', 'Welcome'
], 'zh-CN');
// 切换语言
await this.ui18nService.switchLanguage('en-US');
}
}
```
#### 响应式状态
```typescript
export class MyComponent implements OnInit {
currentLanguage$ = this.ui18nService.currentLanguage$;
isInitialized$ = this.ui18nService.isInitialized$;
isLoading$ = this.ui18nService.isLoading$;
stats$ = this.ui18nService.stats$;
ngOnInit() {
// 监听语言变化
this.currentLanguage$.subscribe(language => {
console.log('当前语言:', language);
});
// 监听翻译统计
this.stats$.subscribe(stats => {
if (stats) {
console.log('翻译统计:', stats);
}
});
}
}
```
### UI18nTranslateDirective
翻译指令,用于模板中的文本翻译。
```html
<!-- 基础用法 -->
<div ui18nTranslate="Hello World"></div>
<!-- 指定目标语言 -->
<div ui18nTranslate="Hello World" ui18nLang="en-US"></div>
<!-- 设置fallback文本 -->
<div ui18nTranslate="Hello World"
ui18nFallback="默认文本"
ui18nLoading="翻译中..."></div>
<!-- 用于输入框placeholder -->
<input ui18nTranslate="请输入用户名" type="text">
```
### UI18nTranslatePipe
翻译管道,用于模板表达式中的翻译。
```html
<!-- 基础用法 -->
<p>{{ 'Hello World' | ui18nTranslate }}</p>
<!-- 指定目标语言 -->
<p>{{ 'Hello World' | ui18nTranslate:'en-US' }}</p>
<!-- 在插值表达式中使用 -->
<h1>{{ title | ui18nTranslate }}</h1>
```
### LanguageSelectorComponent
语言选择器组件,提供用户友好的语言切换界面。
```html
<!-- 基础用法 -->
<ui18n-language-selector></ui18n-language-selector>
<!-- 自定义配置 -->
<ui18n-language-selector
[languages]="customLanguages"
[showSearch]="true"
[showNativeName]="true"
[showBothNames]="false"
[disabled]="false"
searchPlaceholder="搜索语言..."
noResultsText="未找到匹配的语言"
(languageChange)="onLanguageChange($event)">
</ui18n-language-selector>
```
#### 自定义语言列表
```typescript
export class MyComponent {
customLanguages = [
{ code: 'zh-CN', name: '简体中文', nativeName: '简体中文', flag: '🇨🇳' },
{ code: 'en-US', name: 'English (US)', nativeName: 'English (US)', flag: '🇺🇸' },
{ code: 'ja-JP', name: '日本語', nativeName: '日本語', flag: '🇯🇵' }
];
onLanguageChange(language: string) {
console.log('语言已切换到:', language);
}
}
```
## 🎨 样式定制
### 使用CSS变量定制主题
```css
/* 在全局样式中定义 */
:root {
--ui18n-primary-color: #3b82f6;
--ui18n-border-color: #d1d5db;
--ui18n-background-color: white;
--ui18n-text-color: #1f2937;
--ui18n-hover-color: #f3f4f6;
}
/* 深色主题 */
[data-theme="dark"] {
--ui18n-primary-color: #60a5fa;
--ui18n-border-color: #374151;
--ui18n-background-color: #1f2937;
--ui18n-text-color: #f9fafb;
--ui18n-hover-color: #374151;
}
```
### 完全自定义组件
```typescript
// 创建自定义语言选择器
@Component({
selector: 'custom-language-selector',
template: `
<div class="custom-selector">
<button
*ngFor="let lang of languages"
(click)="selectLanguage(lang.code)"
[class.active]="lang.code === (currentLanguage$ | async)">
{{ lang.flag }} {{ lang.name }}
</button>
</div>
`
})
export class CustomLanguageSelectorComponent {
currentLanguage$ = this.ui18nService.currentLanguage$;
languages = [
{ code: 'zh-CN', name: '中文', flag: '🇨🇳' },
{ code: 'en-US', name: 'English', flag: '🇺🇸' }
];
constructor(private ui18nService: UI18nService) {}
async selectLanguage(language: string) {
await this.ui18nService.switchLanguage(language as any);
}
}
```
## 🏭 企业级配置
### 企业版初始化
```typescript
// app.module.ts
import { UI18nModule } from '@ui18n/angular';
@NgModule({
imports: [
UI18nModule.forRoot({
config: {
// 基础配置
defaultLanguage: 'zh-CN',
supportedLanguages: ['zh-CN', 'en-US', 'ja-JP'],
// 服务模式
serviceMode: 'hybrid',
enableSmartRouting: true,
// AI提供商
aiProvider: {
type: 'openai',
apiKey: 'your-api-key',
model: 'gpt-4'
},
// 批量优化
enableBatchOptimization: true,
batchConfig: {
maxBatchSize: 50,
debounceDelay: 300
},
// 成本控制
budgetConfig: {
dailyBudget: 100,
warningThreshold: 0.8
},
// 版本控制
enableVersionControl: true,
versionConfig: {
enableIncrementalUpdates: true,
conflictResolution: 'smart-merge'
}
},
autoInitialize: true
})
]
})
export class AppModule {}
```
### 监控和统计
```typescript
@Component({
template: `
<div class="stats-dashboard">
<div *ngIf="stats$ | async as stats">
<h3>翻译统计</h3>
<p>总翻译数: {{ stats.totalTranslations }}</p>
<p>成功率: {{ stats.successRate }}%</p>
<p>缓存命中率: {{ stats.cacheHitRate }}%</p>
<p>平均响应时间: {{ stats.averageResponseTime }}ms</p>
<p>今日成本: ${{ stats.dailyCost }}</p>
</div>
</div>
`
})
export class StatsDashboardComponent {
stats$ = this.ui18nService.stats$;
constructor(private ui18nService: UI18nService) {}
}
```
## 🔧 高级用法
### 自定义翻译拦截器
```typescript
@Injectable()
export class TranslationInterceptor {
constructor(private ui18nService: UI18nService) {}
async intercept(text: string, targetLanguage: string): Promise<string> {
// 预处理
const processedText = this.preProcess(text);
// 执行翻译
const result = await this.ui18nService.translate(processedText, targetLanguage);
// 后处理
return this.postProcess(result.translatedText);
}
private preProcess(text: string): string {
// 自定义预处理逻辑
return text.trim();
}
private postProcess(text: string): string {
// 自定义后处理逻辑
return text;
}
}
```
### 懒加载模块集成
```typescript
// feature.module.ts
@NgModule({
imports: [
UI18nModule.forFeature() // 特性模块使用forFeature()
]
})
export class FeatureModule {}
```
## 🚨 错误处理
```typescript
@Component({
template: `
<div *ngIf="error" class="error-message">
{{ error }}
</div>
`
})
export class MyComponent {
error: string | null = null;
async translateWithErrorHandling() {
try {
const result = await this.ui18nService.translate('Hello World', 'zh-CN');
console.log(result.translatedText);
} catch (error) {
this.error = '翻译失败,请稍后重试';
console.error('翻译错误:', error);
}
}
}
```
## 📱 响应式设计
语言选择器组件内置响应式设计,在移动设备上自动适配。
```css
/* 自定义响应式样式 */
@media (max-width: 640px) {
.ui18n-language-selector {
width: 100%;
}
}
```
## 🌍 无障碍支持
组件内置无障碍支持,包括:
- 键盘导航支持
- 屏幕阅读器支持
- 高对比度模式支持
- 减少动画支持
## 📄 许可证
MIT License - 详见 [LICENSE](../../LICENSE) 文件
## 🔗 相关链接
- [UI18n核心包](../core)
- [React集成包](../react)
- [Vue集成包](../vue)
- [CLI工具](../cli)
- [完整文档](../../docs)
---
**如果这个包对你有帮助,请给我们一个 ⭐ Star!**