欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

如何在Angular8.0下使用ngx-translate进行国际化配置

程序员文章站 2022-03-20 15:05:23
一. 将ngx-translate添加到angular应用程序中 npm install @ngx-translate/core @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 -->
  <h1>{{ 'demo.title' | translate }}</h1>

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

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。