[Angular] Import TranslateModule in Angular 16

1.Background

Angular 更新至V16版后,支援 standalone,故移除了 NgModule,而TranslateModule 又要在AppModule中 import,那该如何做呢?

2.NPM packages installation

复制代码
npm install @ngx-translate/core
npm install @ngx-translate/http-loade

3.Import TranslateModule in bootstrapApplication of main.ts

TypeScript 复制代码
// import ngx-translate and the http loader
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClient, HttpClientModule } from '@angular/common/http';

// required for AOT compilation
export function HttpLoaderFactory(http: HttpClient): TranslateHttpLoader {
  return new TranslateHttpLoader(http);
}

bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(
      NzMessageServiceModule,
      NzDrawerServiceModule,
      NzModalModule,
      TranslateModule.forRoot({
        loader: {
          provide: TranslateLoader,
          useFactory: HttpLoaderFactory,
          deps: [HttpClient]
        }
      })
    )
  ]
}).catch(err => console.error(err));

4. Create i18n files under assets folder.

For example: i18n\en.json, i18n\zh_CN.json, i18n\zh_TW.json

5. Add key value object in i18n files.

For example: en.json

javascript 复制代码
{
    "test": {
        "title": "This is a test title."
    }
}

zh_CN.json

javascript 复制代码
{
    "test": {
        "title": "这是一个测试标题."
    }
}

zh_TW.json

javascript 复制代码
{
    "test": {
        "title": "這是一個測試標題."
    }
}

6. Import TranslateService service and TranslateModule module.

TypeScript 复制代码
import { TranslateModule, TranslateService } from '@ngx-translate/core';

...

imports: [NzButtonModule, NzSelectModule, TranslateModule, CommonModule, FormsModule, NzCardModule, NzFormModule, NzInputModule]

...

  constructor(private translate: TranslateService) {
    this.translate.setDefaultLang('en');
    this.translate.use('en');
    this.selectedLang = 'en';
  }

7. Using in HTML

html 复制代码
<h1>{{ 'test.title' | translate }}</h1>

8. Using in component

TypeScript 复制代码
const lang = this.translate.instant(key);

9. Change language

TypeScript 复制代码
changeLanguage(): void {
    let lang = this.translate.getDefaultLang();
    this.translate.setDefaultLang(this.selectedLang);
    this.translate.use(this.selectedLang);
  }

10. The full source code

TypeScript 复制代码
import { CommonModule } from '@angular/common';
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzCardModule } from 'ng-zorro-antd/card';
import { NzFormModule } from 'ng-zorro-antd/form';
import { NzInputModule } from 'ng-zorro-antd/input';
import { NzSelectModule } from 'ng-zorro-antd/select';

@Component({
  selector: 'app-pages-sample-translate',
  template: `
    <br />
    <h1>{{ 'test.title' | translate }}</h1>
    <br />
    <nz-select [(ngModel)]="selectedLang" (ngModelChange)="log($event)">
      <nz-option nzLabel="English" nzValue="en"></nz-option>
      <nz-option nzLabel="简体中文" nzValue="zh_CN"></nz-option>
      <nz-option nzLabel="繁體中文" nzValue="zh_TW"></nz-option>
    </nz-select>
    <button nz-button nzType="primary" (click)="changeLanguage()">{{ 'test.changelang' | translate }}</button>
    <button nz-button (click)="getLang('test.changelang')">Get lang with Component</button>
  `,
  styles: [
    `
      nz-select {
        width: 200px;
      }
    `
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
  standalone: true,
  providers: [],
  imports: [NzButtonModule, NzSelectModule, TranslateModule, CommonModule, FormsModule, NzCardModule, NzFormModule, NzInputModule]
})
export class TranslateComponent implements OnInit {
  selectedLang: any = {};

  constructor(private translate: TranslateService) {
    this.translate.setDefaultLang('en');
    this.translate.use('en');
    this.selectedLang = 'en';
  }

  ngOnInit(): void {}

  changeLanguage(): void {
    let lang = this.translate.getDefaultLang();
    this.translate.setDefaultLang(this.selectedLang);
    this.translate.use(this.selectedLang);
  }

  log(value: any): void {
    this.changeLanguage();
  }

  getLang(key: string): void {
    const lang = this.translate.instant(key);
    console.log(lang);
  }
}

11. Test result

相关推荐
电商API_180079052474 分钟前
电商商品价格监控工具淘宝京东商品价格抓取API项目实操分享
java·大数据·开发语言·前端·数据挖掘
sxmas15 分钟前
用状态机与DAG建模四阶段业务流程:以MIND模型为例
前端
倔强的石头1061 小时前
【Linux指南】动静态库系列(七):符号表与重定位:链接器如何把函数调用接起来
linux·前端·javascript
a1117762 小时前
3D 脑图谱 / Bilingual 3D Brain Atlas 项目
前端
T1mzhou2 小时前
ARM64 Linux 6.10内核启动流程2-rootfs 怎么挂上
linux·服务器·前端
小小尚@3 小时前
WebGIS/ECharts 地图开发|MapLand 在线行政区划边界一键下载 GeoJSON 工具
前端·javascript·echarts
默_笙4 小时前
🚍 一条 Todo 的奇幻漂流:TypeScript 全栈类型安全的"护照检查"
前端·javascript
计算机魔术师4 小时前
NVIDIA 以 129.3 亿美元收购 Hugging Face
前端
平头哥技术团队4 小时前
Day 01 | 用 HTML 写第一个网页:双击就能在浏览器打开
前端
计算机魔术师5 小时前
两年翻45倍!英伟达靠买买买建成千亿投资帝国
前端