Tips on maintaining consistent language between two Angular components for a father and son relationship

I am facing an issue with language selection in my Angular project. I have two components, home.components (father) and room.component.ts (son), which support both English and Spanish languages.

When I switch the language in the room component and then navigate back to the home component, the selected language is not maintained consistently across both components.

How can I resolve this issue? Should I use output() and input()? Or should I leverage Angular's lifecycle hooks?

home.component.ts

    <ul class="navbar-nav  navbar-right">
                    <span class="form-inline">
                        <select 
                            class="form-control" 
                            #selectedLang 
                            (change)="switchLang(selectedLang.value)">
                          <option *ngFor="let language of translate.getLangs()" 
                            [value]="language"
                            [selected]="language === translate.currentLang">
                            {{ language }}
                          </option>
                        </select>
                      </span>        

                </ul>

<div *ngIf="translateEn == true; then thenBlock else elseBlock"></div>
                        <ng-template #thenBlock>     <p class="title-room">{{ room.title }}</p></ng-template>
                        <ng-template #elseBlock> <p class="title-room">{{ room.titleEs }}</p></ng-template>


switchLang(language: string) {
    this.translate.use(language);
    this.translateEn = language === 'en';
    this.translate.currentLang;
    console.log('current' ,this.translate.currentLang);
  }

room.component.ts

<div *ngIf="translateEn == true; then thenBlock3 else elseBlock3"></div>
            <ng-template #thenBlock3>     <p><span class="bold-data">{{'RoomType' | translate}}</span> {{ room.roomtype }}</p></ng-template>
            <ng-template #elseBlock3> <p><span class="bold-data">{{'RoomType' | translate}}</span> {{ room.roomtypeEs }}</p></ng-template>


  switchLang(language: string) {

    this.translate.use(language);
    this.translateEn = language === 'en';
    this.translate.currentLang;
    console.log('current' ,this.translate.currentLang);

}

Answer №1

If you want to manage the selected language in your application, consider creating a LanguageService with a BehaviorSubject.

LanguageManager:

@Inject({
  provideIn: "root"
})
export class LanguageManager {

  private _selectedLanguage: BehaviorSubject<string>;
  
  constructor (
    private readonly TranslateService: TranslationService
  ) {
    this._selectedLanguage = new BehaviorSubject("EN"); // Default language
    TranslateService.use("EN");
  }

  set selectedLanguage(value: string) {
    this._selectedLanguage.next(value);
    this.TranslateService.use(value);
  }

  public getSelectedLanguage$(): Observable<string> {
    return this._selectedLanguage.asObservable();
  }

  public getCurrentSelectedLanguage(): string {
    return this._selectedLanguage.getValue();
  }

}

This setup allows you to access the current language either as an Observable or directly as a string for easy reference of the active language. It is recommended to inject this service in the main AppComponent.

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

TypeScript Add Extract Kind

I am currently working on implementing a function called sumPluck. This function will allow the user to specify a property of type number from an object in an array, and then calculate the sum of all those properties. For example: type A = { prop: number ...

The ngIf statement in the template isn't functioning properly after a refresh; instead, it is causing a redirection to the homepage

I've been developing with Angular 7, trying to display a <div> ... </div> based on multiple values that I declared as : Boolean = false; in the .ts file. These values are updated in ngOnInit, but for some reason, the page keeps redirecting ...

Error TS2604: Upon importing the 'material-ui' button from one package into another

Our team is in the process of implementing a new front-end for our application by transitioning from standard react to typescript. As someone who is relatively new to development, I have been struggling with a particular issue for several days now. The set ...

Developing an NPM package within a yarn workspace monorepo featuring internal dependencies

Currently, I am working on a project where I am utilizing yarn workspace to develop a library that will eventually be published on NPM. This library has a dependency on a private core package within the same workspace. As per my understanding, the workspac ...

Creating a visually appealing stacked bar chart using Chart.js in Angular 9 with multiple bars

Upon integrating Chart.js into my Angular 9 application, I encountered an issue where the expected chart values were not being displayed. In order to address this problem, I need to structure the barChartData according to the format showcased in this stac ...

Tailor TypeScript to support various JavaScript versions

One of the advantages of TypeScript is the ability to target different versions of Javascript globally - allowing for seamless switching between transpiling ES3, ES5, or ES6. For browsers like IE that require ES3 support, it serves as the lowest common de ...

How to showcase the array object nested within an array of objects in Angular 2

Here is the content of my JSON file: country_id:String, name:String scholardetails:[{ country_id:String, scholarshipname:String, scholarshiplink:String }] ...

Extract the data from a deeply nested key within a JSON object

I'm currently working on a function that takes a key (specified as a string) and retrieves its corresponding values from a given JSON object. Here is the JSON data I am working with: [ { "some_key1": [ {"key": "va ...

What is the reason for ngbDatepicker converting numbers into dates upon input?

This specific HTML snippet has a unique feature: when the input number is set to "2", it automatically changes to 04.01.2001: <div class="input-group"> <input [ngClass]="{'invalid-input': editFor ...

The Ng2AutoCompleteModule library, which contains the ng2-auto-complete module, was not correctly processed by ngcc or is not compatible with Angular Ivy

I am in the process of upgrading Angular from version 2 to 15 and encountering an error. Can anyone provide assistance with this issue? It seems that the ng2-auto-complete library, which declares Ng2AutoCompleteModule, has not been processed correctly by ...

What is the best way to experiment with transclusion (ng-content) in Angular2?

I have a specific component that I need to test, here is the code: import {Component, OnInit, Input} from "@angular/core"; @Component({ selector: 'column', template: '<ng-content></ng-content>', host: { ...

Looking for a youtube.d.ts file to integrate the youtube-iframe-api with Angular 2?

My current challenge involves implementing the youtube iframe api for seamless video snippet display and control within an Angular 2 application. Maintaining TypeScript's type concept is crucial for both the webpack compiler and myself :). A brief ov ...

Creating a welcome screen that is displayed only the first time the app is opened

Within my application, I envisioned a startup/welcome page that users would encounter when the app is launched. They could then proceed by clicking a button to navigate to the login screen and continue using the app. Subsequently, each time the user revisi ...

Collaborating ASP.NET MVC and WebAPI token sharing

Within my ASP.NET MVC and Angular2 application, I rely on Identity Server 3 for user authentication. The usual process involves users logging into the MVC application, which then saves the token in a cookie. Once logged in successfully, users can perform ...

What methods should I employ to effectively test a custom icon function?

I've written a function that creates a Leaflet icon with specified properties: createIcon( url, retinaUrl: string = null, height: number = 20, width: number = 20 ): Icon { const icon: Icon = L.icon({ iconUrl: url, ico ...

Loading Data in an IONIC List as You Scroll

Is there a way in IONIC using native components to generate a dynamic list? What I mean is being able to load the initial data and rows, display them, and then continue loading additional data as the user scrolls to avoid long loading times for all data ...

Debugger for Visual Code unable to locate URL in Microsoft Office Add-in

I recently installed the Microsoft Office Add-in Debugger VS code extension, but I'm having trouble getting it to work despite following the instructions. Every time I try, an error message pops up: https://i.sstatic.net/h2FYs.png Upon inspecting my ...

What is the proper method for updating _variables in the latest version of Bootstrap, 4.3.1?

I am currently utilizing Bootstrap 4.3.1 within my Angular 8 project and I aim to customize some of the default variables in Bootstrap, such as $font-size-base. Despite attempting the following code, it does not seem to be effective. Can someone provide g ...

Typescript counterpart of a collection of key-value pairs with string keys and string values

Within the API I'm currently working with, the response utilizes a data type of List<KeyValuePair<string, string>> in C#. The structure appears as shown below: "MetaData": [ { "key": "Name", &q ...

What is the correct way to specify an image path for a background URL?

Currently, I am setting a background image for the hr tag using the following code: <hr style="height:6px;background: url(http://ibrahimjabbari.com/english/images/hr-11.png) repeat-x 0 0;border: 0;margin:0px!important"> However, I have now saved th ...