After refreshing, Angular 7 ngx-translate fails to retain the selected language

In our Angular application, we have implemented functionality for two languages: German as the default and English as the alternative. This is made possible through the use of ngx-translate within the translateService.

A common issue occurs when users refresh the browser, causing the application to revert back to the default language.

To address this, the switchLang() function is called from the navigation bar:

<li class="nav-item">
    <a class="nav-link" id="switchLang" (click)="switchLang()">
      <span>
        <i class="fa fa-globe" aria-hidden="true"></i>
        <span>{{'switch-lang' | translate}}</span>
      </span>
    </a>
</li>

The logic behind the switching of languages can be found in the component.ts file:

switchLang() {
    this.languageService.switchLanguage();
}

Furthermore, there is a dedicated language service responsible for managing language settings:

import { Injectable } from '@angular/core';
import {TranslateService} from '@ngx-translate/core';

@Injectable({ providedIn: 'root' })
export class LanguageService {

  private language = 'de';

  constructor(private translateService: TranslateService) { }

  getCurrentLanguage() {
    return this.language;
  }

  getLocale() {
    if (this.language === 'en') {
      return 'en_US';
    } else {
      return 'de_DE';
    }
  }

  switchLanguage() {
    if (this.language === 'en') {
      this.language = 'de';
    } else {
      this.language = 'en';
    }
    this.translateService.use(this.language);
  }
}

The translation functionality is powered by ngx-translate.

Answer №1

Storing the selected language in localStorage (or another storage location) is the correct approach.

Answer №2

If you want to save data in the memory of your device, localStorage is a handy tool. The code snippet below demonstrates how it can be done:

// choose a language
selectLanguage(i: number) {
  this.selectedLang = this.availableLanguages[i];
  this.translationService.use(this.availableLanguages[i].name.toLowerCase());
  localStorage.setItem("selectedLanguage", this.availableLanguages[i].name.toLowerCase());
}

Answer №3

An Angular service resides solely in memory. To introduce persistence, you can either store the current value in localStorage during a language switch or save the setting to the server.

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

React: Content has not been refreshed

MarketEvent.tsx module is a centralized controller: import * as React from 'react'; import EventList from './EventList'; import FullReduce from './FullReduce'; import './MarketEvent.less' export default class Mark ...

Transforming the navigation menu using CSS, HTML, and jQuery

One challenge I am facing involves creating a menu similar to the one on http://edition.cnn.com/. I want the clicked button in the menu to receive focus, while the others lose it. Despite trying various methods, I have not been successful. Can someone off ...

Interactions between a service and a directive: interdependence or triggering of events

Issue: managing multiple directives that interact with a service or factory to communicate and log actions with a server. Should I establish dependencies between them? angular.module('someModule', []) .directive('someDir', ['l ...

I am currently attempting to hide a tab and its corresponding sections on the Dynamics 2011 CRM form upon loading

I have been working on a Dynamics 2011 CRM form where I am attempting to hide a tab and its sections from the onload event. Even though my code runs without any errors, the tab always remains visible. It seems like the custom code I wrote works initially ...

Monitor the links that have been clicked using JavaScript cookies

I have a website with three pages in total. On the first page, there is a button that leads users to the second page when clicked. At the second page, users are given the option to add an 'addon' to their order or skip it. After making their ch ...

I'm having trouble with an error in my React project on VS Code. Can anyone provide guidance

Could you please explain the meaning of this error message: errno: 'ENOENT', code: 'ENOENT', syscall: 'spawn cmd', path: 'cmd', spawnargs: [ '/s', '/c', 'start', '""', ...

Issue with Aligning Datepicker Interface

Displayed above its corresponding input element or sometimes vertically anywhere on the page. I am looking to have it appear below the input element instead. https://i.sstatic.net/nEDwc.png https://i.sstatic.net/pVbhG.png Currently, it is overlapping it ...

Using AJAX to retrieve additional JavaScript code or functions from the server

It's common knowledge that AJAX is often utilized to request a web part in HTML format from the server. However, is it feasible to use AJAX to request a script that includes functions? ...

Ways to display JSON in a structured format on an HTML page

Is there a way to display JSON in a formatted view on my html page? The JSON data is coming from a database and I want it to be displayed neatly like the following example: { "crews": [{ "items": [ { "year" : "2013", "boat" ...

Setting limits to disable or remove specific times from the time picker input box in Angular

I'm having trouble with a time input box. <input type="time" min="09:00" max="18:00" \> Even though I have set the min and max attributes to values of 09:00 and 18:00 respectively, it doesn't seem to be working properly. I want to ...

Steps to refresh a variable when the SMS read plugin successfully completes

I'm attempting to make a post call within the success callback of my SMS read plugin code. I can successfully print _this.otpnumber in the console. Please refer to my stack trace image link getSMS(){ var _this= this; var fil ...

Transferring information from AJAX to PHP script with the click of a button

Simply put, I am in the process of adding a pop-up update panel to my to-do website using an HTML button. The website already has a login-register system and uses MySQL queries to display different tables for each user. The update buttons on the website c ...

Ensure the md-sidenav remains open by default

I have set up a md-sidenav in my project. I would like the sidenav to be open by default, while still maintaining an overlay effect on the page and allowing users to close the sidenav, thus avoiding the use of md-is-locked-open. Any suggestions on how I ca ...

What is the correct way to extract a value from a keyvalue pair?

When dealing with an object that returns boolean "issues", I specify it as a string. If the value is true, I aim to show a checkmark; if false, I want to display a cross. <ul *ngFor="let filtered of reposFiltered | keyvalue"> <li *ngIf=& ...

A guide to retrieving users that have been tagged in a post using VUE-NODE

What i currently have: I have created separate inputs for title, body, and mention user. What i desire: My goal is to implement a functionality similar to Facebook or Twitter where users can be mentioned using the @ symbol in the post body (users must b ...

What could be causing my Angular app to be unable to locate the embedded component?

This particular component is called HomeTabComponent and it is embedded here. @Component({ selector: 'app-home-tab', templateUrl: './home-tab.component.html', styleUrls: ['./home-tab.component.scss'] }) export class Ho ...

Learning how to utilize the angular2 promise `then` callback in TypeScript

Recently, I've started exploring TypeScript and I'm facing a challenge in optimizing a specific line of code. The scenario involves filtering an array received from a callback function that is passed to a promise.then()... getAllItems(): Promis ...

Error Continues - "Exceeding Header Size Error"

In my current Next.js project, I have integrated a login system using NextAuth. Initially, everything was running smoothly. However, I started encountering an error whenever I attempted to retrieve the session. The Error: https://pastebin.com/Mh624N3c Du ...

Insert placeholder text without access to the input field

Is it possible to activate a placeholder in a component that is outside of the current context? For example: <foreign-component [config]="someConfig" placeholder="somePlaceholder"></foreign-component> The <foreign-compo ...

Confirming the PayPal contribution made by two external parties

Currently, I am in the process of developing a project that will enable users to send donations to one another. Instead of creating my own donation system from scratch, I am considering integrating Paypal. However, given the nature of the system, I must e ...