nt
@bigbear713/nb-trans
npm i @bigbear713/nb-trans
nt

@bigbear713/nb-trans

an angular(2+) component about i18n.

by bigBear713

14.0.0 (see all)License:MITTypeScript:Built-In
npm i @bigbear713/nb-trans
Readme

@bigbear713/nb-trans

Angular translation lib by bigBear713.

OnlineDemo

Bug Report

Feature Request

Document


Changelog


Feature

  • Support to direct/lazing loading translated file;
  • Support to update translated content in page directly and no need to reload page;
  • Support to reset the max retry time when failure to load the translated file;
  • Support there are some params in translated sentence;
  • Support there are some components in the translated sentence;
  • Support the changeDetection of components as ChangeDetectionStrategy.OnPush;

Version

The nb-trans's major version will keep up with the Angular's major version
  • "@bigbear713/nb-trans":"^12.0.0" - "@angular/core": "^12.0.0"
  • "@bigbear713/nb-trans":"^13.0.0" - "@angular/core": "^13.0.0"
  • "@bigbear713/nb-trans":"^14.0.0" - "@angular/core": "^14.0.0"

Installation

$ npm i @bigbear713/nb-trans
// or
$ yarn add @bigbear713/nb-trans

Module

NbTransModule

Translation module. After importing the module, you can use the componentpipe. And service also can be used if you don't import the module, the default is root.

NbTransTestingModule

Translation test module, it is for Unit Test.

Services

NbTransService

v12.0.0
It is a service to provide the translate feature.
Properties
PropertiesTypeDescriptionVersion
langstringCurrent language valuev12.0.0
loadDefaultOverbooleanWhether the translated file of the default language is loadedv12.0.0
Methods
NameReturnDescriptionScenesVersion
changeLang(lang: string)Observable<INbTransChangeLang>Switch language. The lang param should be same as the key of NB_TRANS_LOADER. It is an Observable event. The result will not be returned until the translated text of the switched language has been loaded. It does not need to unsubscribe, because it will auto be completed when switching the language, whether it is success or failure to switch. The details return result follow the definition of INbTransChangeLang below.When you need to swithc languagev12.0.0
changeLangSync(lang: string)voidSwitch language. The lang param should be same as the key of NB_TRANS_LOADER. It is a sync event, but it is not guaranteed to succeed and when to success.When you just want to do the switch behavior, don't care about the result of it.v12.0.0
getBrowserLang()deprecatedstring | undefinedGet the first language of browserWhen you only want to know what is the language of browser pagev12.0.0
NbTransService.getBrowserLang()string | undefinedGet the first language of browserWhen you only want to know what is the language of browser pagev12.1.0
getBrowserLangs()deprecatedreadonly string[]| undefinedGet a language array known to the user, by order of preferenceIf you need to known the languages known to the userv12.0.0
NbTransService.getBrowserLangs()readonly string[]| undefinedGet a language array known to the user, by order of preferenceIf you need to known the languages known to the userv12.1.0
translationAsync(key: string, options?: INbTransOptions)Observable<string>Get translated text asynchronously based on key and options. The options params is optional, the detail configs follow the definition of INbTransOptions below. And the return value is Observable. When it has not been unsubscribed, switching the language, the translated text will be subscribed so that getting the newest text. Don't forget to unsubscribe itYou can use the observable value in template. And it is recormmend to use it with async pipe.v12.0.0
translationSync(key: string, options?: INbTransOptions)stringSynchronously get translated text according to key and options. The options params is optional, the detail configs follow the definition of INbTransOptions below. Because it is sync function, the translated text will be return immediately. When switching the language, you should recall the function to get the new lang's translated textThe text for temporary use, like when creating a modal via service, and setting the title of the modal.v12.0.0
subscribeLangChange()Observable<string>An subscribe event of switching language. It will return an Observable value, so you can know the newest lang immediately if it does not be unsubscribed when the language has been switched.When you should do something when the lang has been switched.v12.0.0
subscribeLoadDefaultOver()Observable<boolean>Whethe the translated file of default lang has been load over. If success to load the file, you will subscribe true value, otherwise it is false. It will auto be completed after loading over (success or not), so you do not need to unsubscribe itWhen preparing the date of whole project, you can use it. It better to display the tranlated content when user view the page.v12.0.0
Usage
constructor(private transService: NbTransService) {}

// switch language, async event, here need to call subscribe()
this.transService.changeLang(lang).subscribe(result=>{
    // the result after switching language
});

// switch language, sync event, not guaranteed to succeed
this.transService.changeLangSync(lang);

NbTransService.transService.getBrowserLang(); // 'en'

NbTransService.transService.getBrowserLangs(); // ['en']

// async to translate text. can subscribe the translated text, also can use it with async pipe in template
const trans$ = this.transService.translationAsync('title');
trans$.subscribe(trans=>{
    // trans is the text which is translated
});

// sync to tranlate text
const trans = this.transService.translationSync('title'); // trans is the text which is translated

// subscribe lang change, when the language has been switched, here can be done and get the newest language
this.transService.subscribeLangChange().subscribe(lang=>{
      // the lang is the newest language
});

// subscribe the default lang's translation file over. when load over, it will be done, and get the load result
this.transService.subscribeLoadDefaultOver().subscribe(over=>{
      // the over is the result of the load event
});

Components

<nb-trans></nb-trans>

v12.0.0
When you need to translate the sentence which include components. When the lang has been switched, the content will auto be updated.
Input
NameTypeDefaultDescriptionVersion
componentsTemplateRef<{ content: string | TemplateRef<any>; list?: INbTransSentencePart[] }>[][]The corresponding component in the translated text.v12.0.0
keystring''The key to get translated textv12.0.0
optionsINbTransOptions{}The options of translation. The detail config follow the below definition of INbTransOptionsv12.0.0
Usage
<!-- only trans key -->
<nb-trans key="title"></nb-trans>
<nb-trans [key]="transKey"></nb-trans>

<!-- trans key and options -->
<nb-trans key="title" [options]="options"></nb-trans>
<nb-trans key="helloWorld" [options]="({prefix:'content'})"></nb-trans>

<!-- trans key, options and components -->
<nb-trans [key]="complexContent" [options]="options" [components]="[com1,com2]"></nb-trans>
<ng-template #comp1 let-compContent="content">
  <span>{{compContent}}</span>
</ng-template>
<ng-template #comp2 let-compContent="content" let-compList="list">
  <ng-container *ngTemplateOutlet="compContent,context:{list}"></ng-container>
</ng-template>

[nb-trans-subcontent]

v12.0.0
It is a common solution when the sentence include some nested componets (you can impletement yourself to meet the requirement). It will render the nested content. The selector is attribute, and can be used in <div />, <span />, <a /><ng-container /> and others. The component is used with <nb-trans></nb-trans>, don't use it alone.
Input
NameTypeDefaultDescriptionVersion
nb-trans-subcontentstring | TemplateRef<any>''The content will be rendered. It accept the string or TemplateRef type. When the content is string, it will be render directly, and the input property: subcontentList will be ignored. When the content is TemplateRef, the subcontentList param will work.v12.0.0
subcontentListINbTransSentencePart[][]Only when the nb-trans-subcontent is TemplateRef, and the content is the input property of <nb-trans></nb-trans>, it will work. The [nb-trans-subcontent] component will use it as the template's context.v12.0.0
Usage
<!-- used with <nb-trans></nb-trans> component -->
<!-- demo: This is a sentence: <0>component1</0>.<1> <0>component1 of component2</0> other part of component2 </1>.<2>component3</2> -->
<nb-trans [key]="complexContent" [components]="[comp1,comp2,comp3]"></nb-trans>
<ng-template #comp1 let-comContent="content" let-list="list">
  <b [nb-trans-subcontent]="comContent" [subcontentList]="list"></b>
</ng-template>
<ng-template #comp2 let-comContent="content" let-list="list">
  <app-widget [comContent]="comContent" [list]="list"></app-widget>
</ng-template>
<ng-template #comp3 let-comContent="content">
  <b>{{comContent}}</b>
</ng-template>

Pipes

nbTrans: transform(key: string, options?: INbTransOptions): string

v12.0.0
The pipe which to tranlate the text. It can be used in template, and get the translated text via key. When the language has been switched, the content in here will auto be updated.
Params
NameTypeMandatoryDescriptionVersion
keystringtrueThe key to get tranlated textv12.0.0
optionsINbTransOptionsfalseThe translated config. The detail configs follow the definition of INbTransOptions belowv12.0.0
Return
TypeDescription
stringThe translated text
Usage
<!-- only key param -->
<div>{{'title'|nbTrans}}</div>

<!-- key and options params -->
<div>{{'title'|nbTrans:options}}</div>
<div>{{'helloWorld'|nbTrans:({prefix:'content'})}}</div>

Tokens

NB_TRANS_DEFAULT_LANG

string
v12.0.0
The default lang. When initial the instance of NbTransService, it will auto to load the default lang's translated content. The value is NbTransLangEnum.ZH_CN when you do not set it in AppModule. It will be set in AppModule in common
Usage
  providers: [
    // ...
    {
      provide: NB_TRANS_DEFAULT_LANG,
      useValue: NbTransLangEnum.ZH_CN,
    },
    // ...
  ]

NB_TRANS_LOADER

{ [key: string]: INbTransLoader }
v12.0.0
The loader of translated text. Support to direct/lazing load. It will be set in AppModule in common
  • Direct load: import the translated text directly, and used to be the value of the language. Direct load will make the init files size be bigger.
  • Lazing load: load the translated file via http.get() or import(). When the file's format is json, you can use http.get() to load.
Usage
Direct load
  providers: [
    // ...
    {
      provide: NB_TRANS_LOADER,
      useValue: {
        [NbTransLangEnum.ZH_CN]: zhCNTrans,
        [NbTransLangEnum.EN]: enTrans,
      }
    }
    // ...
  ]
Lazing load
  • When the file is json format
  providers: [
    // ...
    {
      provide: NB_TRANS_LOADER,
      useFactory: (http: HttpClient) => ({
        // dyn load and the content is a json file
        // the loader fn return value can be Observable<Object>/Promise<Object> type
        // [NbTransLangEnum.EN]: () => http.get('./assets/localization/en/translations.json').toPromise(),
        [NbTransLangEnum.EN]: () => http.get('./assets/localization/en/translations.json'),
        // [NbTransLangEnum.ZH_CN]: () => http.get('./assets/localization/zh-CN/translations.json').toPromise(),
        [NbTransLangEnum.ZH_CN]: () => http.get('./assets/localization/zh-CN/translations.json'),
      }),
      deps: [HttpClient]
    }
    // ...
  ]
  • When the file is ts format
  providers: [
    // ...
    {
      provide: NB_TRANS_LOADER,
      useValue: {
        [NbTransLangEnum.EN]: () => import('./localization/en/translations').then(data => data.trans),
        [NbTransLangEnum.ZH_CN]: () => import('./localization/zh-CN/translations').then(data => data.trans),
      }
    }
    // ...
  ]

NB_TRANS_MAX_RETRY_TOKEN

number
v12.0.0
The max retry time when failure to load translated file. The default is 5. It will be set in AppModule in common.
Usage
  providers: [
    // ...
    {
      provide: NB_TRANS_MAX_RETRY_TOKEN,
      useValue: 3
    },
    // ...
  ]

Interfaces

INbTransLoader

v12.0.0
The translated file loader
PropertyTypeMandatoryDescriptionVersion
[langKey: string]Object | (() => (Observable<Object> | Promise<Object>))falseThe key is string type, the value is the language in common. The value of loader is object which include the translated text, or is Observable/Promise which will return the object which include the translated text.v12.0.0

INbTransOptions

v12.0.0
The config of translation
PropertyTypeMandatoryDescriptionVersion
prefixstringfalseThe prefix of trans key. The prefix value will be append to the front of the key. So there is a new key and will be used to get translated text.v12.0.0
paramsINbTransParamsfalseThe params in the translated text.v12.0.0
returnKeyWhenEmptybooleanfalseIt is used to config whether to return key value when can't get the translated text by the key. The default is true. When you set it as false, it will return whitespace string.v12.0.0

INbTransParams

v12.0.0
The params in the translated text
PropertyTypeMandatoryDescriptionVersion
[key: string]stringfalseThe key and value are string typev12.0.0

INbTransChangeLang

v12.0.0
The result of switching language
PropertyTypeMandatoryDescriptionVersion
resultbooleantrueThe result of switching language. It is true when success to switch, otherwise it is falsev12.0.0
curLangstringtrueCurrent language. If failure to switch language, it is the previous language, otherwise it is the language you want.v12.0.0

INbTransSentencePart

v12.0.0
The sentence part, it may be string or INbTransSentenceCompPart type. The sentence is string when it is string; The sentence include component and need to be parsed when it is INbTransSentenceCompPart. The component can handle it in common, you do not need to concern the logic

INbTransSentenceCompPart

v12.0.0
The part which include component in sentence
PropertyTypeMandatoryDescriptionVersion
indexnumbertrueThe index of components which is the input prop components of <nb-trans />v12.0.0
contentstringtrueThe translated text contentv12.0.0
listINbTransSentencePart[]falseThe parsed content of sentencev12.0.0

Enums

NbTransLangEnum

v12.0.0
The enum of common language. You can not use it if you don't like, because only use it to set the default lang in lib (you can overwrite it), it is not used anywhere.

NbTransSentenceItemEnum

v12.0.0
The enum of sentence item. When parsing the translated sentence, it will be as the type:STR, COMP or MULTI_COMP.

Contribution

Feature and PR are welcome to make this project better together

bigBear713


License

MIT

Downloads/wk

226

GitHub Stars

32

LAST COMMIT

6mos ago

MAINTAINERS

1

CONTRIBUTORS

1

OPEN ISSUES

1

OPEN PRs

0
VersionTagPublished
14.0.0
latest
2mos ago
No alternatives found
No tutorials found
Add a tutorial

Rate & Review

100
No reviews found
Be the first to rate