簡體   English   中英

打字稿Angular中的ngx-translate用法

[英]ngx-translate usage in typescript Angular

我正在使用這個@ngx-translate/core 和@ngx-translate/http-loader i18n 服務,它在模板(.html)中運行良好

{{'title'|translate}}

現在我想翻譯我的組件打字稿文件(.ts),但我不知道如何使用它。

我在構造函數中注入 translateService

constructor(private translate: TranslateService) {}

.component.ts

//update employee
editClick(item){
console.log(item);
this.emp=item;
this.ModalTitle="Edit Employee";  <-- Need to translate this using pipe
this.ActivateAddEditEmpComp=true;
}

//delete employee
deleteClick(item){
if(confirm('Are you sure??')){  <-- Need to translate this using pipe
  this.service.deleteEmployee(item.EmployeeId).subscribe(data=>{
    alert(data.toString());
    this.refreshEmpList();
  })
}
}

首個進口翻譯服務

import { TranslateService } from '@ngx-translate/core';

在構造函數中注入:

constructor(
    public translate: TranslateService,
  )

你可以創建一個函數,或者無論如何你想使用內聯,你可以做這樣的事情。

translationMsg(key) {
    this.translate.get('key').subscribe((data) => {
      return data;
    });
  }

對於您的用例,您可以這樣做

this.ModalTitle = this.translationMsg('Edit_Employee');

您可以使用即時,也可以使用 get 方法,稍后可以訂閱。

this.ModalTitle = this.translate.instant('EDIT_EMPLOYEE') 

第二種方法:

this.translate.get('EDIT_EMPLOYEE').subscribe((data) => {
  this.ModalTitle = data;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM