在Angular8.0下使用ngx-translate进行国际化配置的方法

发布时间:2021-02-03 13:38:21 作者:小新
来源:亿速云 阅读:282

小编给大家分享一下在Angular8.0下使用ngx-translate进行国际化配置的方法,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

一. 将ngx-translate添加到Angular应用程序中

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

二.在app.module.ts中初始化翻译TranslateModule

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

import { AppComponent } from './app.component';

// 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';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,

    // ngx-translate and the loader module
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    })
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

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

三.在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 {
  constructor(private translate: TranslateService) {
    translate.setDefaultLang('en');
  }
}

四.在assets/i18n文件下创建让我们为英文翻译创建相关语言JSON文件,如en.json文件

{
 "demo.title": "Translation demo",
 "demo.text": "This is a simple demonstration app for ngx-translate"
}

五.在app.component.html中使用

<div>
  <!-- translation: translation pipe -->
  <h2>{{ 'demo.title' | translate }}</h2>

  <!-- translation: directive (key as attribute)-->
  <p [translate]="'demo.text'"></p>

  <!-- translation: directive (key as content of element) -->
  <p translate>demo.text</p>
</div>

看完了这篇文章,相信你对“在Angular8.0下使用ngx-translate进行国际化配置的方法”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. 在iis下配置php的方法
  2. 在windows下使用python进行串口通讯的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

angular8 ngx-translate

上一篇:使用Python实现issubclass的方法

下一篇:怎么让docker中的mysql启动时自动执行sql语句

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》