angular使用i18n / angular i18n的基础配置

学习自:https://blog.csdn.net/qq_36671474/article/details/100042765

下载安装依赖

npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader 

folder图 ( 代码涉及一下文件 - 更改 / 新增 )

在这里插入图片描述

app.component.html

<h1>
    <span> test the i18n module: ngx-translate</span>
    <h1>{{ 'hello' | translate }}</h1>
</h1>

app.component.ts

import { Component } from '@angular/core';
//新增
import { TranslateService } from '@ngx-translate/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'myNGdemo1';
  //新增
  constructor(public translateService: TranslateService) {}
  //新增
  ngOnInit(): void {
    this.translateService.addLangs(["zh","en"]);
    this.translateService.setDefaultLang("en");
    const browserLang = this.translateService.getBrowserLang();
    this.translateService.use(browserLang?.match('/zh|/en') ? browserLang : 'zh');
  }
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
//新增
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { TranslateModule, TranslateLoader, TranslateService } from '@ngx-translate/core';
//新增
export function TranslateLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, "./assets/i18n/", ".json");
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    //新增
    HttpClientModule,
    TranslateModule.forRoot({
      loader: [{
        provide: TranslateLoader,
        useFactory: (TranslateLoaderFactory),
        deps: [HttpClient]
      }]
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

assets/i18n

/en.json
{
  "hello": "the word is hello"
}

/zh.json
{
  "hello": "你好"
}

environment

export const environment: any = {
  production: true,
  supportedLocale: ["en-US", "zh-CN", "id", "vi"],
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值