Update the language setting on-the-fly in Angular 7 without the need to refresh the application

Is there a way to change the Locale_Id in my angular app during runtime without using window.location.reload() to update the locale?

I need to implement a solution where I can switch locales dynamically without having to reload the entire application.

Below is the code snippet:

app.module

import { LOCALE_ID } from '@angular/core';
import { LocaleService} from "./services/locale.service";

@NgModule({
    imports: [//imports],
    providers: [
        {provide: LOCALE_ID,
         deps: [LocaleService],
         useFactory: (LocaleService: { locale: string; }) => LocaleService.locale
        }
    ]})

locale.service

import { Injectable } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import localeEnglish from '@angular/common/locales/en';
import localeArabic from '@angular/common/locales/ar';

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

    private _locale: string;

    set locale(value: string) {
        this._locale = value;
    }
    get locale(): string {
        return this._locale || 'en';
    }

    registerCulture(culture: string) {
        if (!culture) {
            return;
        }
        this.locale = culture;

        switch (culture) {
            case 'en': {
                registerLocaleData(localeEnglish);
                break;
            }
            case 'ar': {
                registerLocaleData(localeArabic);
                break;
            }
        }
    }
}

app.component

import { Component } from '@angular/core';
import { LocaleService} from "./services/locale.service";

@Component({
  selector: 'app-root',
  template: `
    <p>Choose language:</p>
    <button (click)="english()">English</button>
    <button (click)="arabic()">Arabic</button>
  `
})
export class AppComponent {

  constructor(private session: LocaleService) {}

  english() {
    this.session.registerCulture('en');
    window.location.reload(); // <-- I don't want to use reload
  }

  arabic() {
    this.session.registerCulture('ar');
    window.location.reload(); // <-- I don't want to use reload
  }
}

Answer №1

Instead of reloading the page, you can simply add a delay before ending the registerCulture function.

For instance:

english() {
    spinner.show();  // <-- display loader
    setTimeout(() => {
            this.session.registerCulture('en');
            spinner.hide();  // <-- hide the loader
          }, 1000);    
    // window.location.reload();
  }

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

Passing a boolean as the value for a Material UI MenuItem in a React TypeScript application

I am encountering an issue as a beginner in react with passing a simple boolean value as a prop for the MenuItem component in the material UI library. I believe the solution is not too complex. Can someone provide guidance on how to fix this error? The sp ...

Updating a variable in Nuxt 3 using vue.js

Recently, I started experimenting with Nuxt 3 and Vue 3. All I want is a simple value change when clicking on my div tag. <a id="change" @click="changeValue()">{{value}}</a> <script lang="ts" setup> let val ...

Incorporating a Link/Template Column into Your Unique Table Design

I built a table component following the guidelines from this article: Creating an Angular2 Datatable from Scratch. While I have added features like sorting and paging to suit my app's needs, I am struggling with implementing a "Template column" to al ...

Next.js v13 and Firebase are encountering a CORS policy error which is blocking access to the site.webmanifest file

Background: I am currently developing a website using Next.js version 13 in combination with Firebase, and I have successfully deployed it on Vercel. Upon inspecting the console, I came across two CORS policy errors specifically related to my site.webmani ...

The error message "TypeError: Object(...) is not a function" is indicating an issue when attempting to

Here is my code from addevent.ts: export class EventPage { eventDetail = {} as EventDetail; eventDetailRef$: AngularFireList<EventDetail>; constructor(public navCtrl: NavController, public navParams: NavParams, private database: AngularFireData ...

Can someone explain why the Next 13 API route is showing up as empty?

I am currently working with Next 13 and I am attempting to create a simple API route. My goal is to have a: "hi" returned when I visit localhost:3000/api/auth. Despite not encountering a 404 error or any errors in the terminal or console, I can&a ...

Use ngClass to combine a function call with a basic string in Angular

Currently, I am working with Angular and facing an issue while attempting to generate multiple div elements using ngFor. All the divs share the same class obtained from a function call, with the last div having an additional 'no-margin' class. T ...

The element did not match the Angular Routing selector "app-home"

How can I prevent my initial component from being loaded twice in Angular? I am trying to implement a default/empty component to avoid the AppComponent being loaded within itself. The empty component would serve as the starting point for loading other comp ...

Maintain the spacing of an element when utilizing *ngFor

Using Angular.js and *ngFor to loop over an array and display the values. The goal is to preserve the spaces of elements in the array: string arr1 = [" Welcome Angular ", "Line1", "Line2", " Done "] The ...

What causes npm start to fail in Angular 6 after incorporating social login functionality?

I am currently working on integrating Social Login functionality into my app. I have attempted to incorporate the following: npm install --save angular-6-social-login-fixed npm install --save angular-6-social-login npm install --save angular-6-social-log ...

React, redux, and redux observable are all essential tools for developing web applications. They

I am currently working on determining the type of a promise's resolve function. Here is a snippet of the code, or you can find it on GitHub: https://github.com/Electra-project/Electra-Desktop/blob/master/src/app/header/epics.ts export function getSt ...

React Hot Toast useState is unfortunately not exported from the React library

While working on a Next.js project, I encountered an issue when trying to use react-hot-toast. When I attempted to import it into any file, I received the following error message: Error - ./node_modules/react-hot-toast/dist/index.mjs Attempted import erro ...

Angular6: Generating a dynamic list of radio buttons with unique identifiers

I have a challenge in creating a dynamic list of radio buttons from a JSON array. While I can successfully do that, the specific requirement is to assign a unique ID to each radio button generated. The structure of my JSON data is as follows: this.employe ...

The date in a nodejs application appears to be shifted by one day

Despite similar questions being asked before here, the solutions provided did not resolve my issue. Here is the scenario I am dealing with: https://i.sstatic.net/H9rcO.png Upon clicking save, I collect data from certain fields to generate a date using th ...

Is it possible to drive without nest.js?

I currently have a node-ts-express-setup that does not utilize nest.js. Unfortunately, the documentation and examples for drivine do not provide setup instructions without nest.js. Is there a way to use drivine without having to include nest as a dependen ...

Leveraging Ignorable Fields in Angular 2 Reactive Forms

Can Angular 2's reactive forms support adding ignorable fields? For example, consider the following Form: this.form = new FormGroup({ subTasks: new FormArray([]), }); Each subTask requires user input and the solution is stored in the FormArray. ...

Effortless spring picture sharing thanks to @onetoonemapping

After uploading an image, I receive an image_id. However, when I use that id to upload a product, the product table shows an empty value in the image_id field. If you're unable to replicate the issue, you can access the code here. This is the struct ...

Having difficulty pushing Angular project to Github

Trying to push my angular project to Github has been a bit challenging. The project's structure consists of: backend (Node API) frontend (Angular) .gitignore To push the angular project, I navigated to the root folder and ran the following commands: ...

What is the best way to link function calls together dynamically using RXJS?

I am seeking a way to store the result of an initial request and then retrieve that stored value for subsequent requests. Currently, I am utilizing promises and chaining them to achieve this functionality. While my current solution works fine, I am interes ...

Angular JSON converter - Transform XML data to JSON format

Struggling to convert XML API response to JSON using xml2js library, facing issues with getting 'undefined' in the console. Here is my API service: export class WordgameService { public apiUrl = "http://www.wordgamedictionary.com/api/v1/reference ...