Internationalization (i18n) and Localization in Angular with .NET Core

Introduction

Internationalization (i18n) and Localization (l10n) in Angular with .NET Core can be implemented to support multiple languages and regional settings in your application. Here's a step-by-step guide to achieve this.

Step 1. Set Up the Angular Application

Create a new Angular project.

ng new AngularI18nApp
cd AngularI18nApp

Install the necessary packages.

npm install @ngx-translate/core @ngx-translate/http-loader

Set up ngx-translate, Create a folder src/assets/i18n, and add JSON files for each language (e.g., en.json, fr.json).

Example en.json

{
  "HELLO": "Hello"
}

Example fr.json

{
  "HELLO": "Bonjour"
}

Modify app.module.ts to configure ngx-translate.

import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
// Required for AOT compilation
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
}
@NgModule({
  declarations: [
    // Your components here
  ],
  imports: [
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    }),
    // Other imports here
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Use the translation service in your components.

import { Component } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
  selector: 'app-root',
  template: `
    <div>
      <h1>{{ 'HELLO' | translate }}</h1>
      <button (click)="changeLanguage('en')">English</button>
      <button (click)="changeLanguage('fr')">Français</button>
    </div>
  `
})
export class AppComponent {
  constructor(private translate: TranslateService) {
    translate.setDefaultLang('en');
  }
  changeLanguage(lang: string) {
    this.translate.use(lang);
  }
}

Step 2. Set Up the .NET Core Backend

Create a new .NET Core Web API project.

dotnet new webapi -n DotNetI18nApp
cd DotNetI18nApp

Install the necessary NuGet packages.

dotnet add package Microsoft.Extensions.Localization
dotnet add package Microsoft.AspNetCore.Localization

Configure localization services in Startup.cs.

public void ConfigureServices(IServiceCollection services)
{
    services.AddLocalization(options => options.ResourcesPath = "Resources");
    services.Configure<RequestLocalizationOptions>(options =>
    {
        var supportedCultures = new List<CultureInfo>
        {
            new CultureInfo("en"),
            new CultureInfo("fr")
        };
        options.DefaultRequestCulture = new RequestCulture("en");
        options.SupportedCultures = supportedCultures;
        options.SupportedUICultures = supportedCultures;
    });
    services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseRouting();
    var localizationOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>().Value;
    app.UseRequestLocalization(localizationOptions);
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Create resource files for localization.

  1. Create a folder called Resources in the project root.
  2. Add resource files like Controllers.HomeController.en.resx and Controllers.HomeController.fr.resx.

Example Controllers.HomeController.en.resx

<root>
  <data name="Greeting" xml:space="preserve">
    <value>Hello from .NET Core!</value>
  </data>
</root>

Example Controllers.HomeController.fr.resx

<root>
  <data name="Greeting" xml:space="preserve">
    <value>Bonjour de .NET Core!</value>
  </data>
</root>

Create a controller to use localized strings.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Localization;
[ApiController]
[Route("[controller]")]
public class HomeController : ControllerBase
{
    private readonly IStringLocalizer<HomeController> _localizer;
    public HomeController(IStringLocalizer<HomeController> localizer)
    {
        _localizer = localizer;
    }
    [HttpGet]
    public IActionResult Get()
    {
        var greeting = _localizer["Greeting"];
        return Ok(new { message = greeting });
    }
}

Step 3. Connect Angular Frontend to .NET Core Backend

Make HTTP requests from Angular to the .NET Core backend.

Use Angular's HttpClient to call the backend API and get localized messages.

import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  template: `
    <div>
      <h1>{{ message }}</h1>
      <button (click)="changeLanguage('en')">English</button>
      <button (click)="changeLanguage('fr')">Français</button>
    </div>
  `
})
export class AppComponent {
  message: string;
  constructor(private http: HttpClient) {
    this.changeLanguage('en');
  }
  changeLanguage(lang: string) {
    this.http.get(`/home?culture=${lang}`).subscribe((data: any) => {
      this.message = data.message;
    });
  }
}

Configure the backend to handle culture parameters.

Modify the Configure method in Startup.cs to read the culture from query parameters:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseRouting();
    var supportedCultures = new[] { "en", "fr" };
    var localizationOptions = new RequestLocalizationOptions()
        .SetDefaultCulture(supportedCultures[0])
        .AddSupportedCultures(supportedCultures)
        .AddSupportedUICultures(supportedCultures);
    app.UseRequestLocalization(localizationOptions);
    app.Use(async (context, next) =>
    {
        var cultureQuery = context.Request.Query["culture"];
        if (!string.IsNullOrWhiteSpace(cultureQuery))
        {
            var culture = new CultureInfo(cultureQuery);
            CultureInfo.CurrentCulture = culture;
            CultureInfo.CurrentUICulture = culture;
        }
        await next.Invoke();
    });
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Summary

By following these steps, you can successfully set up internationalization and localization in an Angular application with a .NET Core backend. The Angular app will handle client-side translations using ngx-translate, while the .NET Core backend will serve localized strings based on the selected culture.