Angular ngx-translate: Responding to language change event

Is it possible to detect the change in the "current language" using the ngx-translate library? Which JavaScript event should I use to accomplish this task?

To clarify, please refer to this straightforward example: https://stackblitz.com/edit/github-yvbmgu

I am looking to identify the alteration of the currentLang from the "diff" component during the ngOnInit() lifecycle.

Answer №1

If you want to stay updated on language changes, you can subscribe to TranslateService's onLangChange observable.

    ngOnInit() {
      console.log(this.translate.currentLang);
      this.translate.onLangChange.subscribe((event: LangChangeEvent) => {
        console.log(event.lang);
      });
    }

Check out the TranslateService API for more information.

Answer №2

If you want to detect language changes in Angular, you can utilize Angular's own BehaviorSubject. Simply implement the following code in a General Service:

public langObsevable: BehaviorSubject<string> = new 
BehaviorSubject<string>(null);

public onLanguageChanged(lang: string){
    this.langObsevable.next(lang);
}

Subsequently, you can subscribe to these language changes in other components by doing the following:

this.generalService.langObsevable.subscribe(res => {
    translate.use(res);
});

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

Converting a specific string format to a Date object in TypeScript

I am in need of a solution to convert strings with the given format into Date objects using TypeScript: var dateTimeString:string = "20231002-123343" I have created my own method as shown below: var dateTime:string[] = dateTimeString.split(" ...

Formatting dates in Angular 2 and handling them in MongoDB with Express

I am currently working with Angular 2 and ExpressJS along with MongoDB. I have a date format that is being retrieved as 2016-06-02T14:20:27.062Z, but I need to display it in the format 06/02/2016 14:20:27 Express: In models/user.js: var userSchema = Sch ...

Error: The variable "redirectTo" has not been declared. This error can be found in the

I recently embarked on my journey to learn Angular2. I diligently followed the documentation and watched some helpful YouTube tutorials to guide me through the process. However, I've hit a roadblock while trying to configure the routes in my project. ...

Creating a TypeScript generic record with specified keys

I need to validate in TypeScript whether an object contains the specified keys (from SingleShopColumns or MultishopColumns) and has a validations property that is an array of strings. I am using Record and generics, but any simple method of representing t ...

"Upload a video file and use JavaScript to extract and save the first frame as an image

I have a webpage where users can upload a video file, and the page will generate a thumbnail based on a timestamp provided by the user. Currently, I am focusing on generating the thumbnail from the FIRST frame of the video. Here is an example of my progr ...

Invoking a nested class while declaring types in TypeScript

This is the specific format of data that I am in need of this.structure=[ { id: 1, name: 'root1', children: [ { id: 2, name: 'child1' }, { id: 3, name: 'child2' } ] }, { ...

Prevent Typescript from flagging unnecessary warnings about unassigned values that will never be assigned

One of my functions serves as a shortcut for selecting values from synchronous observable streams. The function in its entirety looks like this: export function select<T>(inStream: Observable<T>): T { let value: T; race( inStream, ...

Angular is having trouble locating the module for my custom library

Trying to implement SSR in my angular application, but encountering an error when running npm run build:ssr. I've created my own library named @asfc/shared, which is bundled in the dist folder. ERROR in projects/asfc-web/src/environments/environment. ...

Zod implements asynchronous validation for minimum, maximum, and length constraints

When working with Zod, setting values can be done as shown below: z.string().max(5); z.string().min(5); z.string().length(5); However, in my scenario, the values (e.g., 5) are not predetermined. They are fetched from an API dynamically. How can I create t ...

Create a reusable React component in Typescript that can handle and display different types of data within the same

I have a requirement to display four different charts with varying data types. For instance, interface dataA{ name: string, amount: number } interface dataB{ title: string, amount: number } interface dataC{ author: string, amount: ...

Issues have arisen with the functionality of Ionic2-Calendar on the device

I'm currently working on a project that involves developing an Ionic 4 app with Angular 8. I've encountered a peculiar issue while using this calendar plugin. It seems similar to the problem discussed in this thread. Despite reaching out for sol ...

How to effectively utilize TypeScript in a team environment using both Atom and VSCode?

Our team utilizes TypeScript with both Atom and VSCode as our editors, but we are facing challenges with the tsconfig.json file. VSCode is not recognizing the typings, causing the namespace for 'ng' (for Angular 1.x) to be unknown in VSCode. Wh ...

Implementing Firebase as an Authentication Middle Layer for Express.js

I am currently working on developing an authentication middleware to verify the presence of a valid firebase token in the request header. Here's the code snippet: auth.ts import * as firebase from 'firebase-admin'; import { NextFunction, Re ...

The issue of footer overlapping the login form is observed on iOS devices while using Safari and Chrome

Unique ImageI am currently working on an Angular 8 project with Angular Material. I have successfully designed a fully functional login page. However, I am encountering a problem specifically on iOS devices such as iPhones and iPads, whether it is Safari o ...

How can you retrieve the preceding sibling using an Angular directive?

Currently, I am utilizing ELEMENTREF to interact with the DOM via Renderer2. Allow me to provide a simple example: import { Directive, Renderer2, ElementRef } from '@angular/core'; @Directive({ selector: '[appHighlight]' }) export c ...

Enhance your bootstrap accordion by incorporating stylish up and down arrows using the <accordion> element

I am currently developing a sophisticated web application using Angular and TypeScript, and I have decided to incorporate accordions in some sections. The setup for these accordions involves TypeScript/Bootstrap as shown below: <accordion> <acco ...

Angular and Bootstrap work hand in hand to provide a seamless user experience, especially

I have been exploring ways to easily close the modal that appears after clicking on an image. My setup involves using bootstrap in conjunction with Angular. <img id="1" data-toggle="modal" data-target="#myModal" src='assets/barrel.jpg' alt=&a ...

Exploring Angular 2 Tabs: Navigating Through Child Components

Recently, I've been experimenting with trying to access the HTML elements within tabs components using an example from the Angular 2 docs. You can view the example here. Here is a snippet of my implementation: import {Component, ElementRef, Inj ...

Module fails to load in the proper sequence

As a .NET developer who is relatively new to modern client-side web applications, I am currently working on developing an Angular2 charting application using Chart.js. The modules are being loaded with SystemJS. Below is the content of my systemjs.config. ...

Using both Angular material design and Bootstrap together can provide a seamless

Is it feasible to integrate material design into an Angular app alongside bootstrap without any complications? I am aiming to leverage the grid system of twitter-bootstrap and incorporate the dialogues from material design... ...