Switching languages in Angular2 i18n

Seeking a solution to

  • dynamically set the current language for display: I have followed the latest angular recipe for internationalization as outlined here, which states "the user's language is hardcoded as a global document.locale variable in the index.html"

How can this be achieved dynamically in angular2 + typescript?

My attempt from the official Angular2 plunkr version: https://plnkr.co/edit/lWV4VhzpWYnCXeDBpzsn?p=preview where I've commented out the

document.locale='en';

I tried accessing the window.document within a typescript service to change the locale there, but even though it is called and the locale is properly set (as shown in the console), the interface does not appear in the selected language at startup.

Furthermore, since the incorrect method is used and the display is not refreshed, the dropdown buttons do not work either; resolving this issue will be the next step.

Answer №1

I store the chosen language key by the user in local storage:

//<select name="selectLanguage" (change)="onChange($event.target.value)">
 public onChange(languageKey: string): void {
    localStorage.setItem('languageKey', languageKey);
    location.reload(true);
  }

Next, I trigger a reload and in i18n.provider.ts

let selectedLanguage = localStorage.getItem('languageKey');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Error message: 'ng' command cannot be found even after completing the installation of Node

Recently, I set up a fresh MacOS Catalina operating system on my computer. When I attempted to run my old project using 'ng serve', I encountered the error message 'ng: command not found'. To troubleshoot, I installed npm 6.12.1 via nod ...

Adding dynamic row values to a bootstrap table in angular 4 - what's the best approach?

When using an Angular 4 bootstrap table, I am encountering an issue where only the first row value is displayed in the table from the backend when entering a product in the text box and pressing enter. Even though the alert window shows the data for the se ...

Error Encountered in Nextjs 14: Cookies Unreachable in axiosInstance or apiService Files

After transitioning to Nextjs from React, I found the architecture of Nextjs to be quite different and confusing. In my current project, I am attempting to authorize API CRUD operations using a token stored in a cookie. However, when trying to retrieve the ...

What is the best method to compare two times and determine if they fall on the same date within an Angular 2/4 application? The time should be in the format of "HH:mm AM

Is there a way to validate if my time period falls on the same date? let startTime = currentSelection.startTimeHr + ":" + currentSelection.startTimeMin + " " + currentSelection.startTimeAMPM; let endTime = currentSelection.stopTimeHr + ":" + currentSele ...

Tips for creating unit tests for methods in Angular components with jasmine

As a beginner in jasmine unit testing, I am struggling to understand how to write and implement tests in jasmine. I have been encountering numerous errors along the way. Is there anyone who can assist me with writing a unit test for the code snippet below ...

Enhance your text in TextInput by incorporating newline characters with advanced editing features

I'm encountering an issue with my Textarea component that handles Markdown headers: type TextareaProps = { initValue: string; style?: StyleProp<TextStyle>; onChange?: (value: string) => void; }; type OnChangeFun = NativeSynthetic ...

How can I resolve the issue of TypeScript AngularJS component modal where the function this.$modalInstance.dismiss is not working?

After converting one of my user data entry forms into a uib-modal, I encountered an issue when trying to close the modal using the "cancel" button. The error message "this.$modalInstance.dismiss is not a function" keeps popping up. The same problem occurs ...

Typescript Error: lib.d.ts file not found

Recently, I experimented with Typescript and utilized the Set data structure in this manner: var myset = new Set<string>(); I was pleasantly surprised that there was no need for additional libraries in Typescript, and the code worked smoothly. Howe ...

The Google Books API has reached its limit for requests

Encountering a rate limit exceeded error from the Google Books API while using this demo: To reproduce, open the developer console in Chrome and perform some searches. The rate limit errors will be displayed in the console. [],"lazyUpdate":null},"status" ...

Error TS2339: Property does not exist on type 'object' - Typescript arrow function issue

In my experience with Angular, I have noticed that I encounter typescript compile errors quite often when using fat arrow functions within an rxjs stream. Despite being able to run the app and having it transpile successfully, I am curious about how to re ...

Using react-scripts leads TypeScript to mistakenly search for the incorrect file to import

Currently utilizing React and Relay in my project, I've encountered an issue with TypeScript. After relocating the directory where Relay generates some TypeScript files that are included in my app, TypeScript is unable to find them, presenting an unus ...

How to pass environment variables using Angular CLI commands

Is it possible to pass parameters when running angular cli commands such as ng build, or in my case, ng serve, to modify or define variables in the environment without having to edit the environment file or create a new environment each time? For instance ...

The Angular data table is encountering an issue as the dataStream.pipe function is not recognized

I'm currently working on setting up a table using Angular data table, but I've run into an issue related to the dataSource. I'm seeing an error message that says "dataStream.pipe is not a function", and I'm having trouble resolving it. ...

How to transfer an object between sibling components in Angular 4

Being new to Angular 2+, I understand that I may not be approaching this the correct way. My issue involves two sibling components. When clicking on a "link" in one component, it redirects to another controller. My goal is to pass an object to the componen ...

Angular 6 - Issue with ngModel displaying [object Object] instead of data in binding

Within my code, there is a variable named "data" that holds the following information: { id: 1, date: "2018-03-13T16:18:03", date_gmt: "2018-03-13T16:18:03", guid: {}, modified: "2018-05-03T17:25:36", modified_gmt: "2018-05-03T17:25:36", slug: "hello-worl ...

Angular 5 offers the capability to use mat-slide-toggle to easily display and manipulate

I am experiencing an issue with displaying data in HTML using a mat-slide-toggle. The mat-slide-toggle works correctly, but the display does not reflect whether the value is 1 (checked) or 0 (unchecked). Can anyone provide some ideas on how to resolve this ...

Encountering a 404 error while attempting to deploy an Angular demo application in production

While attempting to follow an Angular tutorial on deploying the application locally in production mode, I encountered difficulties even when using the provided sample app. Here are the steps I took: ng new prod-app ng build --prod http-server /dist/prod- ...

What is the process of converting Luxon DateTime format into a string or numerical representation?

After setting up a Luxon clock for my project, I am facing an issue while using a component to define the month number of the current date. import { DateTime } from 'luxon'; import React, { useEffect, useState } from 'react'; interface ...

Rendering Backend Data in Angular Application on Page Refresh with Apache Server Integration

Attempting to deploy an Angular Flask Application demo with Apache. The project directory is located at /var/www/backend/basicapp/. Within this directory, you will find: app.py from flask import Flask, jsonify, render_template from flask_cors import CORS, ...

How can I set up SignalR on the client-side in Angular for the best performance?

My current setup involves using Angular with asp.net core 2.1.3 as the backend. I have added the SignalR configuration package with the following code snippet: services.AddSignalR((hubOptions) => { hubOptions.EnableDetailedErrors = ...