Callum Slater

Callum Slater

1567069781

Angular Localization Using ngx-translate

Originally published by Jeetendra Gund at https://www.telerik.com

In this step-by-step tutorial, I will demonstrate how to create an Angular project and use an ngx-translate library for localization. This tutorial covers the following topics.

  • What are internationalization and localization
  • What is ngx-translate?
  • Create an Angular project
  • Install ngx/translate library
  • Set up the Angular project
  • How to use or work with localization
  • How to get browser language   

What are Internationalization and Localization?

“In computing, internationalization and localization are means of adapting computer software to different languages, regional peculiarities and technical requirements of a target locale.” —Wikipedia

What is ngx-translate?

ngx-translate is the library for internationalization (i18n) and localization in Angular. It simplifies your Angular application to work for localization. It’s easy to set up and use in an Angular application. (For more details, visit GitHub.)

Create an Angular Project

Following are the steps to create the Angular application using CLI:

  • Create an Angular project, using the following CLI command.
> ng new angular-localization-demo 
  • Once this CLI command executes, next move to the created project path using the following command:
> cd my-localization-demo 
  • Run your created application easily using the following command. It directly opens the Angular application in the browser.
> ng serve -o 
  • It will show output as below image in the browser.

Install the ngx-translate Library

Following are the steps to install the ngx-translate library:

  • Open a command prompt and move to your application path.
  • Type the below command to install the npm module:
> npm install @ngx-translate/core --save 
  • There is no loader available by default. You need to do translation manually by using setTranslation, so it’s better to use a loader. There are two ways you can use loader: You can create your own custom loader or use existing one provided by ngx-translate library. In this example we are using an existing one.
  • To use the existing loader, type below command to install the module:
> npm install @ngx-translate/http-loader --save 
  • Finally, we are done with the installation part. Now we can see how to use it in an Angular application.

Set up the Angular Project

To use the ngx-translate library in the Angular application, follow these steps.

  • Open app.module.ts file and import the translate and loader modules as shown in the code below:
import { BrowserModule } from  '@angular/platform-browser';
import { NgModule } from  '@angular/core';
import { AppRoutingModule } from  './app-routing.module';
import { AppComponent } from  './app.component';
// localization module import
import { TranslateModule, TranslateLoader, TranslateService } from  '@ngx-translate/core';
import { TranslateHttpLoader } from  '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from  '@angular/common/http';
 
// loader module
export  function  HttpLoaderFactory(http:  HttpClient) {
  return  new  TranslateHttpLoader(http, './assets/i18n/', '.json');
}
 
@NgModule({
  declarations: [AppComponent],
    imports: [
      BrowserModule,
      AppRoutingModule,
      HttpClientModule,
      TranslateModule.forRoot({
        loader: {
          provide:  TranslateLoader,
          useFactory:  HttpLoaderFactory,
          deps: [HttpClient]
        }
      })
    ],
    exports: [TranslateModule],
    providers: [TranslateService],
    bootstrap: [AppComponent]
})
export  class  AppModule { }
  • In the above code, you can see we have used useFactory, provided the HttpLoaderFactory function to it for automate translation, and provided the locale.json file path to load.
  • It loads translations from ‘/assets/i18n/[lang].json’. Here ‘[lang]’ is the language we are using; for example, for Dutch it would be nl.
  • Create .json file in the above path. Here you can create many files of language you want to support in the application. In this example I have created two files — the first is English(en.json) and second Dutch(nl.json).
  • Finally, we have set up ngx-library to be used in our Angular application.

How to Use or Work with Localization

So far, we have seen how to create an Angular project, install ngx-library, and set it up in the Angular project. Next, we are going to learn how to play with it in components using the library. Following are the basic and simple steps for localization.

  • Open the app.component.ts file, import TranslateService and inject this service in constructor for translation.
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 {
 title = ‘angular-localization-demo’;
 constructor(translate: TranslateService) {}
}

  • Next, add the two lines below in constructor for setting the default language for localization and using it.
translate.setDefaultLang(‘en’);

translate.use(‘en’);

  • In this step we are going to define the translation in .json file to use in localization. Following is the syntax to add translations in .json file; we are storing in key-value pair format.
  • Add in en.json file.
{
 “WelcomeMessage”: “Welcome to Angular Localization Demo”
}
  • Add in nl.json file.
{
 “WelcomeMessage”: “Welkom bij de demo voor hoeklokalisatie”
}
  • Next, we are ready to play with it. We are going to change the current title Welcome to angular-localization-demo! to a localized translation. This translation service we are using as a pipe in HTML. The below code shows how to use in HTML; add it in the app.component.html file.
<h1>
 {{ ‘WelcomeMessage’ | translate }}!
</h1>
  • In the above code, you can see ‘WelcomeMessage’ is the key of .json file, as we see in the previous step after that pipe symbol and object of translation service.
  • Finally, we are done with changes. Now run the application with the following command.
> ng serve -o
  • Once you run the above command you will see the output as below image in the browser.

  • It shows text in English, but now we can change the default language and language to use as ‘nl’ as below code.
this.translate.setDefaultLang(‘nl’);
this.translate.use(‘nl’);

Once you change it as above and check in the browser, you will see the output as below image.

How to Get Browser Language

In the previous steps, we have seen that we have directly set the language in the constructor using the below two statements.

this.translate.setDefaultLang(‘nl’);
this.translate.use(‘nl’);

But, if you want your application localization to work on the basis of browser language, then what? Use the below method of TranslateService to get current browser language to set the default language.

const currentLanguage = this.translate.getBrowserLang();
this.translate.setDefaultLang(currentLanguage);
this.translate.use(currentLanguage);

Once you are done with the above changes, run your application. It will get your first browser language and apply it to the library. If you want to check for other languages, change your browser language from English to Dutch and restart the browser and hit the application URL. It will set Dutch as the language as per browser.

Note: This demo application is only working for English and Dutch language. If you want another language, you need to add that language JSON file and set that language as default.

You can also download this example from here.

Conclusion

In this article, we discussed what ngx_translate is and how to use it in Angular applications. After that we saw how to work with browser languages. If you have any suggestions or queries regarding this article, please contact me.

“Learn it, Share it.”

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

Angular 8 (formerly Angular 2) - The Complete Guide

Angular & NodeJS - The MEAN Stack Guide

The Complete Node.js Developer Course (3rd Edition)

The Web Developer Bootcamp

Best 50 Angular Interview Questions for Frontend Developers in 2019

How to build a CRUD Web App with Angular 8.0

React vs Angular: An In-depth Comparison

React vs Angular vs Vue.js by Example

#angular

What is GEEK

Buddha Community

Angular Localization Using ngx-translate
Einar  Hintz

Einar Hintz

1593235440

Visualizing data with NGX-Charts in Angular

Data Science, Data Analytics, Big Data, these are the buzz words of today’s world. A huge amount of data is being generated and analyzed every day. So communicating the insights from that data becomes crucial. Charts help visualize the data and communicate the result of the analysis with charts, it becomes easy to understand the data.

There are a lot of libraries for angular that can be used to build charts. In this blog, we will look at one such library, NGX-Charts. We will see how to use it in angular and how to build data visualizations.

What we will cover:

  1. Installing ngx-chart.

  2. Building a vertical bar graph.

  3. Building a pie chart.

  4. Building an advanced pie chart.

A brief introduction about NGX-Charts

NGX-Chart charting framework for angular2+. It’s open-source and maintained by Swimlane.

NGX-Charts does not merely wrap d3, nor any other chart engine for that matter. It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functions, scales, axis and shape generators, etc. By having Angular do all of the renderings it opens us up to endless possibilities the Angular platform provides such as AoT, Universal, etc.

NGX-Charts supports various chart types like bar charts, line charts, area charts, pie charts, bubble charts, doughnut charts, gauge charts, heatmap, treemap, and number cards.

Installation and Setup

1. Install the ngx-chart package in your angular app.

npm install @swimlane/ngx-charts --save

2. At the time of installing or when you serve your application is you get an error:

ERROR in The target entry-point "@swimlane/ngx-charts" has missing dependencies: - @angular/cdk/portal

You also need to install angular/cdk

npm install @angular/cdk --save

3. Import NgxChartsModule from ‘ngx-charts’ in AppModule

4. NgxChartModule also requires BrowserAnimationModule. Import is inAppModule.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { NgxChartsModule }from '@swimlane/ngx-charts';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    NgxChartsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Amazing! Now we can start using ngx-chart component and build the graph we want.

In the AppComponent we will provide data that the chart will represent. It’s a sample data for vehicles on the road survey.

#angular #angular 6 #scala #angular #angular 9 #bar chart #charting #charts #d3 charts #data visualisation #ngx #ngx charts #pie

Christa  Stehr

Christa Stehr

1598940617

Install Angular - Angular Environment Setup Process

Angular is a TypeScript based framework that works in synchronization with HTML, CSS, and JavaScript. To work with angular, domain knowledge of these 3 is required.

  1. Installing Node.js and npm
  2. Installing Angular CLI
  3. Creating workspace
  4. Deploying your First App

In this article, you will get to know about the Angular Environment setup process. After reading this article, you will be able to install, setup, create, and launch your own application in Angular. So let’s start!!!

Angular environment setup

Install Angular in Easy Steps

For Installing Angular on your Machine, there are 2 prerequisites:

  • Node.js
  • npm Package Manager
Node.js

First you need to have Node.js installed as Angular require current, active LTS or maintenance LTS version of Node.js

Download and Install Node.js version suitable for your machine’s operating system.

Npm Package Manager

Angular, Angular CLI and Angular applications are dependent on npm packages. By installing Node.js, you have automatically installed the npm Package manager which will be the base for installing angular in your system. To check the presence of npm client and Angular version check of npm client, run this command:

  1. npm -v

Installing Angular CLI

  • Open Terminal/Command Prompt
  • To install Angular CLI, run the below command:
  1. npm install -g @angular/cli

installing angular CLI

· After executing the command, Angular CLI will get installed within some time. You can check it using the following command

  1. ng --version

Workspace Creation

Now as your Angular CLI is installed, you need to create a workspace to work upon your application. Methods for it are:

  • Using CLI
  • Using Visual Studio Code
1. Using CLI

To create a workspace:

  • Navigate to the desired directory where you want to create your workspace using cd command in the Terminal/Command prompt
  • Then in the directory write this command on your terminal and provide the name of the app which you want to create. In my case I have mentioned DataFlair:
  1. Ng new YourAppName

create angular workspace

  • After running this command, it will prompt you to select from various options about the CSS and other functionalities.

angular CSS options

  • To leave everything to default, simply press the Enter or the Return key.

angular setup

#angular tutorials #angular cli install #angular environment setup #angular version check #download angular #install angular #install angular cli

Rakesh Sharma

1590476689

Angular: How to package translation (ngx-translate) with custom library

Hello dear developers, Today in this post I am going to address most important topic about translation service i.e ngx-traslate. Most of the time you have used ngx-translate service in your Angular app to show localization language. If your app is small then it’s pretty simple to implement ngx-translate service by following available ngx-translate documentation.

But in some cases if you are working on large scale app consisting lot of modules and it is using lazy loading module routing strategy then obviously using the translation service which has single en.json (or other) file for the whole app is not a idle way to do it. Because you app is depend on lazy loading module strategy.

So you should have to split this en.json file at module level instead. What do I mean by ‘at module level’ here is that every module has it’s own en.json file which will keep the translations for that particular module only.

Read full article here:
https://festack.blogspot.com/2020/03/angular-how-to-package-translation-ngx.html

#angular #ngx-translate #lazy-loading #translation

Royce  Reinger

Royce Reinger

1658891580

Ruby-gettext: A Pure Ruby Localization(L10n) Library & tool

gettext

gettext for Ruby

Gettext gem is a pure Ruby Localization(L10n) library and tool which is modeled after the GNU gettext package.

This library was called as "Ruby-GetText-Package". Since 2.3.0, this library is called just "gettext". You can call this library as "gettext gem" or "Ruby gettext" to distinguish from GNU gettext.

This library translates original messages to localized messages using client-side locale information(environment variable or CGI variable).

The tools for developers support creating, useing, and modifying localized message files(message catalogs).

Rails support has been removed.

Features

  • Translate singular/plural messages with simple APIs (similar to GNU gettext)
  • Thread safety. Message resources are shared from all threads, but returns translated messages of the current thread's locale.
  • Tools to find message IDs
    • Extract message IDs to po-files using rxgettext from
      • ruby scripts
      • glade-2 XML file (.glade)
      • ERB file (.rhtml, .erb)
      • Anything (with your own parsers)
      • The po-files are compatible with GNU gettext.
    • rmsgfmt creates a mo-file from a po-file. The mo-file is compatible with GNU gettext (msgfmt).
    • Using rxgettext/rmsgfmt as Rake tasks
  • textdomain's scope is adapt to ruby class/module mechanism.
    • A class/module can have plural textdomains.
    • a message is looked up in its class/module and ancestors.
  • CGI support (gettext/cgi)
    • Locale is retrieved from client informations using Ruby-Locale. (HTTP_ACCEPT_LANGUAGE, HTTP_ACCEPT_CHARSET, QUERY_STRING (lang), Cookies (lang)).

Requirements

gem install locale

For development:

  • Racc 1.4.3 or later (for compiling src/rmsgfmt.ry only)

Installation

Uninstall old gettext if exists. (You need to do this when updating 1.93.0 -> 2.0.1)

# sudo/su on POSIX system
gem uninstall gettext

RubyGems

# sudo/su on POSIX system
gem install gettext

Download tar-ball

# De-Compress archive and enter its top directory.
# sudo/su on POSIX system
ruby setup.rb

You can also install files in your favorite directory by supplying setup.rb some options. Try ruby setup.rb --help.

Usage

Translation

_() or gettext(): basic translation method

Translates the message, using the msgid if a translation is not found.

_("Hello") => "Bonjour"  # Found

This translation will appear in the po or pot file as:

msgid: "Hello"
msgstr: "Bonjour"

When a translation is not found it, it will return the msgid. This is a core benefit of gettext and applies to all its translation methods.

_("Hello") => "Hello"  # Not Found

Additional gettext methods come in 3 combinable flavors:

n_() or ngettext(): pluralized

Returns singular or plural form, depending on how many you have.

n_("Apple", "%{num} Apples", n) => "3 Pommes"  # When n = 3
n_("Apple", "%{num} Apple", n)  => "Pomme"     # When n = 1
n_(["Apple", "%{num} Apple"], n)  => "Pomme"   # 2 arg variation

This translation will appear in the po or pot file as:

msgid "Apple"
msgid_plural "%{num} Apples"
msgstr[0] "Pomme"
msgstr[1] "#{num} Pommes"

p_() or pgettext(): context aware

A context is a prefix to your translation, useful when one word has different meanings, depending on its context.

p_("Printer","Open") => "Öffnen" #translation found
p_("Printer","Open") => "Open"   #translation not found

This translation will appear in the po or pot file as:

msgctxt "Printer"
msgid "Open"
msgstr "Öffnen"

Note that the parser when sorting by msgid will strictly sort by the msgid ignoring the msgctxt. If you prefer to sort with the msgctxt you should consider the s_() method.

s_() or sgettext(): without context

The s_() method is very similar to the p_() method except that the context is inside the msgid.

s_("Printer|Open") => "Öffnen" #translation found
s_("Printer|Open") => "Open"   #translation not found
msgid "Printer|Open"
msgstr "Öffnen"

Note the the parser when sorting by msgid will take the context into consideration as it is part of the msgid unlike the p_() method.

Your preference of using s_() or p_() will depend on your translation workflow and process.

Combinations

You can combine n_() with either p_() or s_().

np_() or npgettext(): context aware pluralized

np_("Fruit", "Apple", "%{num} Apples", 3)
np_(["Fruit","Apple","%{num} Apples"], 3) # 2 arg variation
msgctxt "Fruit"
msgid "Apple"
msgid_plural "%{num} Apples"
msgstr[0] ""
msgstr[1] ""

sp_() or spgettext(): context aware pluralized

ns_("Fruit|Apple","%{num} Apples", 3)
ns_(["Fruit|Apple","%{num} Apples"], 3) # 2 arg variation
msgid "Fruit|Apple"
msgid_plural "%{num} Apples"
msgstr[0] ""
msgstr[1] ""

N_() and Nn_(): makes dynamic translation messages readable for the gettext parser

_(fruit) cannot be understood by the gettext parser. To help the parser find all your translations, you can add fruit = N_("Apple") which does not translate, but tells the parser: "Apple" needs translation.

fruit = N_("Apple")   # same as fruit = "Apple"
_(fruit)              # does a normal translation

fruits = Nn_("Apple", "%{num} Apples")
n_(fruits, 3)

Interpolating translations

This is not a feature of gettext but worth noting. You can interpolate translated strings without the ruby String % operator.

N_("active"); N_("inactive"); N_("paused") # possible value of status for parser to find.
_("Your account is #{account_state}.") % { account_state: _(status) }

Bind textdomains to the classes

A textdomain has a translation file in each language. A module/class can have multiple textdomains. This means the libraries/applications can have their own textdomains.

class Foo
  include GetText
  bindtextdomain "your_app_domain_name"
end

class Book
  include GetText
  bindtextdomain "general"
  bindtextdomain "book"
end

Locale

If you need to set the locale by yourself, then use:

GetText.locale = "en_US" # translate into english from now on
GetText.locale # => en_US

Or

include GetText
set_locale "en_US"

For more details and options, have a look at the samples folder.

License

This program is licenced under the same licence as Ruby (See doc/text/ruby-license.txt) or LGPL (Lesser General Public License: doc/text/lgpl-3.0.txt or http://www.gnu.org/licenses/lgpl-3.0.txt).

mofile.rb

Copyright (C) 2001-2009 Masao Mutoh <mutoh at highwhay.ne.jp>
Copyright (C) 2001,2002 Masahiro Sakai <s01397ms at sfc.keio.ac.jp>

gettext.rb

Copyright (C) 2001-2009 Masao Mutoh <mutoh at highwhay.ne.jp>
Copyright (C) 2001,2002 Masahiro Sakai <s01397ms at sfc.keio.ac.jp>

rxgettext

Copyright (C) 2001-2009 Masao Mutoh <mutoh at highwhay.ne.jp>
Copyright (C) 2001,2002 Yasushi Shoji <yashi at atmark-techno.com>

Others

Copyright (C) 2001-2009 Masao Mutoh <mutoh at highwhay.ne.jp>

Translators

LanguageTranslatorStatus
Bosnian (bs)Sanjin Sehic <saserr at gmail.com>1.90.0 (old)
Bulgarian (bg)Sava Chankov <sava.chankov at gmail.com>2.0.1
Catalan (ca)Ramon Salvadó <rsalvado at gnuine.com>2.0.1
Chinese (Simplified)(zh_CN)Yang Bob <bob.yang.dev at gmail.com> (current) 
Yingfeng <blogyingfeng at gmail.com>
2.0.1
Chinese (Traditional)(zh_TW)Yang Bob <bob.yang.dev at gmail.com> (current) 
Lin Chung-Yi <xmarsh at gmail.com>
2.0.1
Croatian (hr)Sanjin Sehic <saserr at gmail.com>1.90.0 (old)
Czech (cs)Karel Miarka <kajism at yahoo.com>1.9.0 (old)
Dutch (nl)Menno Jonkers <ruby-gettext at jonkers.com>1.90.0 (old)
English (default) 2.1.0
Esperanto (eo)Malte Milatz <malte at gmx-topmail.de>2.0.1
Estonian (et)Erkki Eilonen <erkki at itech.ee>2.0.1
French (fr)Vincent Isambart <vincent.isambart at gmail.com> (current) 
David Sulc <davidsulc at gmail.com> 
Laurent Sansonetti <laurent.sansonetti at gmail.com>
2.0.1
German (de)Patrick Lenz <patrick at limited-overload.de> (current) 
Detlef Reichl <detlef.reichl at gmx.org> 
Sven Herzberg <herzi at abi02.de> 
Sascha Ebach <se at digitale-wertschoepfung.de>
2.0.1
Greek (el)Vassilis Rizopoulos <damphyr at gmx.net>2.0.1
Hungarian (hu)Tamás Tompa <tompata at gmail.com>2.0.1
Italian (it)Marco Lazzeri <marco.lazzeri at gmail.com> 
Gabriele Renzi <surrender_it at yahoo.it>
1.6.0 (old)
Japanese (ja)Masao Mutoh <mutomasa at gmail.com>2.1.0
Korean (ko)Gyoung-Yoon Noh <nohmad at gmail.com>1.9.0 (old)
Latvian (lv)Aivars Akots <aivars.akots at gmail.com>2.0.1
Norwegian (nb)Runar Ingebrigtsen <runar at mopo.no>2.0.1
Portuguese (Brazil)(pt_BR)Antonio S. de A. Terceiro <terceiro at softwarelivre.org> (current) 
Joao Pedrosa <joaopedrosa at gmail.com>
2.0.1
Russian (ru)Yuri Kozlov <kozlov.y at gmail.com>2.0.1
Serbian (sr)Slobodan Paunović <slobodan.paunovic at gmail.com>2.0.1
Spanish (es)David Espada <davinci at escomposlinux.org> (current) 
David Moreno Garza <damog at damog.net>
2.0.1
Swedish (sv)Nikolai Weibull <mailing-lists.ruby-talk at rawuncut.elitemail.org>0.8.0 (very old)
Ukrainian (uk)Alex Rootoff <rootoff at pisem.net>2.0.1
Vietnamese (vi)Ngoc Dao Thanh <ngocdaothanh at gmail.com>2.0.1

Maintainer

  • Kouhei Sutou <kou@clear-code.com>

Old maintainer

  • Masao Mutoh <mutomasa at gmail.com>

Links

NOTE: Gettext gem 3.0.0 removed many deprecated APIs and improves internal APIs. We want to keep backward compatibility as much as possible but some existing codes may be broken by gettext gem API change. If your code breaks by gettext gem 3.0.0, please report your problem. We will fix the problem and release a new version.

https://github.com/ruby-gettext/gettext is the official gettext gem repository. It is moved from https://github.com/mutoh/gettext . Mutoh agreed with the move.

Author: Ruby-gettext
Source Code: https://github.com/ruby-gettext/gettext 
License: 

#ruby #localization #text 

Ayyaz Zafar

1624138795

Angular Material Autocomplete - Multiple Use Cases covered

Learn How to use Angular Material Autocomplete Suggestions Search Input. I covered multiple use cases.

Please watch this video. I hope this video would be helpful for you to understand it and use it in your projects

Please subscribe: https://www.youtube.com/channel/UCL5nKCmpReJZZMe9_bYR89w

#angular #angular-material #angular-js #autocomplete #angular-material-autocomplete #angular-tutorial