1.3.0 • Published 9 months ago

@qntm-code/ng-lazy-translate v1.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
9 months ago

@qntm-code/ng-lazy-translate

Lazy loaded translation module for Angular using messageformat.

GitHub release Tests codecov Quality Gate Status Reliability Rating Vulnerabilities Bugs Security Rating Maintainability Rating

Installation

npm i @qntm-code/ng-lazy-translate

Usage - Standalone Components

1. Create providers

import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, appConfig).catch(err => console.error(err));
import { provideHttpClient } from '@angular/common/http';
import { ApplicationConfig } from '@angular/core';
import { provideLazyTranslate } from '@qntm-code/ng-lazy-translate';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(),
    provideLazyTranslate({
      defaultLanguage: 'en',
      languages: [
        {
          code: 'en',
          displayValue: 'English',
        },
        {
          code: 'fr',
          displayValue: 'Français',
        },
      ],
      translationAssetPaths: {
        'en.common': 'asset/i18n/en/common.json',
        'fr.common': 'asset/i18n/fr/common.json',
      },
      missingTranslationHandler: (language: string, key: string) => console.error(`Custom handler: Could not find ${key} in ${language}`),
      missingFileHandler: (namespace: string, language: string) =>
        console.error(`Custom handler: CFile with namespace ${namespace} not found for language ${language}`),
    }),
  ],
};

Usage - Within a Module

1. Import Module

import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { NgLazyTranslateModule } from '@qntm-code/ng-lazy-translate';

@NgModule({
  imports: [
    HttpClientModule,
    NgLazyTranslateModule.forRoot({
      defaultLanguage: 'en',
      languages: [
        {
          code: 'en',
          displayValue: 'English',
        },
        {
          code: 'fr',
          displayValue: 'Français',
        },
      ],
      translationAssetPaths: {
        'en.common': 'asset/i18n/en/common.json',
        'fr.common': 'asset/i18n/fr/common.json',
      },
    }),
  ],
})
export class AppModule {}

2. Import module in component

import { Component } from '@angular/core';
import { NgLazyTranslateModule } from '@qntm-code/ng-lazy-translate';

@Component({
  standalone: true,
  imports: [NgLazyTranslateModule],
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {}

Using pipe in a template

<p>{{ 'common.hello_world' | translate }}</p>

Using the service in a component/service

import { Injectable } from '@angular/core';
import { LazyTranslateService } from '@qntm-code/ng-lazy-translate';

@Injectable()
export class MyService {
  constructor(private readonly translateService: LazyTranslateService) {}

  public doSomething(): Observable<string> {
    return this.translateService.translate('common.hello_world');
  }
}

Dynamically adding translation asset paths

You can dynamically add translation asset paths by calling the addTranslationPaths method on the LazyTranslateService:

import { LazyTranslateService } from '@qntm-code/ng-lazy-translate';

@Injectable()
export class MyService {
  private readonly translateService = inject(LazyTranslateService);

  constructor() {
    this.translateService.addTranslationPaths({
      'en.home': 'assets/i18n/en/home.json',
      'fr.home': 'assets/i18n/fr/home.json',
    });
  }
}

You can also preload all the translation files in the current language by adding the preload paramater to the call:

this.translateService.addTranslationPaths(
  {
    'en.home': 'assets/i18n/en/home.json',
    'fr.home': 'assets/i18n/fr/home.json',
  },
  true
);

LazyTranslateModuleConfig

Whether you use the standalone components or the module, the LazyTranslateModuleConfig options are the same.

OptionTypeDescriptionMandatoryDefault
defaultLanguagestringThe default language to use if no language is specifiedYesN/A
languagesLanguage[]The list of languages to supportYesN/A
translationAssetPathsTranslationAssetPathsThe list of translation assets to load. The key is the language and the translation file name.NoN/A
preloadbooleanWhether to preload all the translation files in the current language.Nofalse
useDefaultLanguagebooleanWhether to use the default language if the specified language is not foundNotrue
enableLoggingbooleanWhether to enable logging of missing translationsNotrue
missingTranslationHandler(language: string, key: string) => voidA custom handler to use when a translation is not found. If not specified, the default handler will be used.NoWill console.error a message
missingFileHandler(namespace: string, language: string) => voidA custom handler to use when a translation file is not found. If not specified, the default handler will be used.NoWill console.error a message

Language

OptionTypeDescription
codestringThe language code.
displayNamestringThe language name.

TranslationAssetPaths

OptionTypeDescription
keystringThe language and translation file name. For example: en.common or fr.app
valuestringThe path to the translation file. e.g assets/i18n/en.common.json

Translation files

Translation files must be in JSON format and have the following structure:

{
  "hello_world": "Hello World!"
}

You can also use nested keys:

{
  "greetings": {
    "hello_world": "Hello World!"
  }
}

You can then access this nest value like so:

  • In a template:

    {{ 'common.greetings.hello_world' | translate }}
  • In a component/service:

    this.translateService.translate('common.greetings.hello_world');

The translation service uses messageformat to format the translation., which allows you to pass values to your translated text:

{
  "greetings": {
    "hello_world": "Hello {name}! It is {time}"
  }
}
  • Template:

    {{ 'common.greetings.hello_world' | translate: { name: 'John', time: '10:00' } }}
  • Component/Service:

    this.translateService.translate('common.greetings.hello_world', { name: 'John', time: '10:00' });

Default value

If you want to provide a default value for when a translation is not found in any language, you can do so by passing it as the last parameter to the translate pipe or function:

  • Template:

    {{ 'common.greetings.hello_world' | translate: { name: 'John', time: '10:00' }: 'Hello, this is my default string' }}

    or without values:

    {{ 'common.greetings.hello_world' | translate: 'Hello, this is my default string' }}
  • Component/Service:

    this.translateService.translate('common.greetings.hello_world', { name: 'John', time: '10:00' }, 'Hello, this is my default string');

    or without values:

    this.translateService.translate('common.greetings.hello_world', undefined, 'Hello, this is my default string');
1.2.0

9 months ago

1.3.0

9 months ago

1.1.6

2 years ago

1.1.5

2 years ago

1.1.4

2 years ago

1.1.3

2 years ago

1.1.2

2 years ago

1.1.1

2 years ago

1.1.0

2 years ago

1.0.0

2 years ago