• angular项目语言切换功能


    1、NzI18nService服务

    参考:https://ng.ant.design/docs/i18n/zh
    

    2、ngx-translate插件

    1)安装依赖
    
    npm install @ngx-translate/core --save
    npm install @ngx-translate/http-loader --save
    
    2)引入TranslateModule模块
    
    *在AppModule中引入TranslateModule模块
    import {TranslateModule} from '@ngx-translate/core';
    
    *根路由引入TranslateModule模块相关配置并在imports中配置如下:
    import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
    import {TranslateHttpLoader} from '@ngx-translate/http-loader';
    import {HttpClient} from '@angular/common/http';
    
    *配置AppModule的 imports如下:
    TranslateModule.forRoot({
           loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                 deps: [HttpClient]
             }
        }),
    
    *最后在模块之外导出 HttpLoaderFactory   
     export function HttpLoaderFactory(http: HttpClient) {
        return new TranslateHttpLoader(http);
     }
    
    3)引入语言json文件
    
    import { Component } from '@angular/core';
    import { TranslateService } from '@ngx-translate/core';
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      isCollapsed = false;
      constructor(public translate: TranslateService) {
        translate.addLangs(['en', 'zh']);
        translate.setDefaultLang('zh');
        const browserLang = translate.getBrowserLang();
        translate.use(browserLang.match(/en|zh/) ? browserLang : 'en');
      }
    }
    
    4)html中使用
    
    {{'app.test' | translate}}
    
    5)页面翻译
    
    引入TranslateService
    import { TranslateService } from '@ngx-translate/core';
    constructor(private translate: TranslateService) {}
    ngOnInit() {
       console.log(this.translate.instant('app.title'))
    }
    

    参考:
    https://stackblitz.com/edit/github-rvuqkx?file=src%2Fapp%2Fapp.module.ts
    https://www.jianshu.com/p/082358d49adc

  • 相关阅读:
    详解ASP.NET的内置对象
    如何架设FTP服务器
    输出JSON问题
    new , virtual , override
    Javascript 操作select控件大全(新增、修改、删除、选中、清空、判断存在等)
    Java回顾之I/O
    数据结构之栈和队列
    Java回顾之多线程同步
    设计模式之行为型模式
    Java回顾之网络通信
  • 原文地址:https://www.cnblogs.com/boreguo/p/13691465.html
Copyright © 2020-2023  润新知