Translate the pipe based on the language specified in the URL using Angular 2

In my Angular2 application, I have a translate pipe. The LanguageComponent is the parent component for all others in which it reads the URL to determine the language and then adds it to the translate service that the pipe uses:

{ path: ':lang', component: LanguageComponent,
    children: [
      { path: 'search', component: SearchComponent },   
    ]}

Although everything functions correctly with the correct values being set in the translate service and parameters, there is an issue in the GUI:

{{ 'label' | translate }}

The problem arises because the pipe is being compiled before the LanguageComponent, causing the 'label' value to default to 'en-us' always.

The translate service functionality is as follows:

public defaultLanguage = 'en-us';
getCurrentLanguage(): any {
   if (this.locale == null) {
     this.locale = window.navigator.language == null ? this.defaultLanguage : window.navigator.language;
   }
   return this.locale;
}

While the route returns the correct value, setting a debugger onInit within LanguageComponent and another one inside the translate service shows that the service's debugger fires up first, reading the default value instead of the URL value.

If anyone knows how to resolve this issue, please advise!

Answer №1

To create a custom pipe similar to Angular's async pipe, you need to follow these steps:

Start by injecting private _ref: ChangeDetectorRef in your pipe's constructor.

In the transform method, store the transformed value in an instance variable and return a WrappedValue that references this variable.

Additionally, subscribe to updates of the current language from a language service. Whenever the language changes, update the instance variable accordingly. Finally, make sure to call this._ref.markForCheck() to trigger re-evaluation of the wrapped value.

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

Is there stability in using *ngFor for lists in Nativescript Angular?

Update: I have inquired about the current status of RadListView in Nativescript, questioning if it still exists. You can find more information here. Initial query: Is it suitable to utilize *ngFor for lists in Nativescript? Typically, I see recommendatio ...

Using React and TypeScript, open the initial tab from a mapped array with an accordion component

{accordion.map(accordionItem => ( <AccordionItem key={accordionItem.title} text={accordionItem.text} title={accordionItem.title} ></AccordionItem> ...

Creating folders and writing data to text files in Angular 4/5 with TypeScript: A tutorial

Is it feasible to create a folder, text file, and write data into that file in Angular5 using Typescript for the purpose of logging errors? Your expertise on this matter would be greatly appreciated. Thank you in advance! ...

There is a Typescript error stating that the argument of type 'NodeListOf<HTMLInputElement> | undefined' cannot be assigned to the parameter of type 'Iterable<HTMLInputElement> ...'

While working on my React/Typescript App, I encountered an issue when trying to access an array of inputs in an event listener using 'e.currentTarget'. To solve this, I utilized Array.from() to convert the NodeListOf into an array and ensured tha ...

Swapping the content of the API response with Angular 11 in the HTML

When the output of row.remarks is 1, I want to display it as "passed" and when it's 0, I want it to be displayed as "fail" in the HTML while using mat-table. HTML <ng-container matColumnDef="remarks"> <th class="font& ...

Make Ionic 2 Navbar exclusively utilize setRoot() instead of pop()

When navigating to a different page, the ion-navbar component automatically includes a back button that uses the pop() method to return to the previous page. Is there a way to modify this behavior so that it utilizes the setRoot() method instead of pop(), ...

A guide to accessing another component's config.ts file in Angular

After following the steps outlined in this tutorial, I successfully created a reusable modal component. However, when trying to personalize it, I encountered an issue where the modal appeared as an empty box and displayed the error ERROR TypeError: ctx_r1. ...

Can the Okta clientId be securely shared in a public repository?

Setting up Okta authentication in an Angular application involves adding a configuration variable with the necessary settings for your OIDC app in the app.module.ts file. You can find more information here. const config = { issuer: 'https://dev-1 ...

Tips for troubleshooting the error message: "The relative import path "$fresh/dev.ts" is not prefaced with / or ./ or ../"

My editor is showing a TypeScript error for a Deno module I am working on. The import path "$fresh/dev.ts" should be prefixed with / or ./ or ../ I have an import_map.json file set up with the following content. { "imports": { "$fre ...

Learn how to store the outcomes of an HTTP operation within array.map() in JavaScript

Having read numerous articles, I am a complete beginner when it comes to async programming and struggling to grasp its concepts. My goal is to map a filtered array of objects and return the result of a function (an amount) to set as the value of pmtdue. De ...

Set up Angular library by downloading from a specified local or network location

If I were to create an Angular library using the following commands: ng new libraries-workspace --create-application=false cd libraries-workspace ng generate library test-library After creating and building the library using the command below: ng build te ...

Is there a way to instruct Alexa/Jovo to incorporate just one render document in its response?

Within my project, there are multiple outputs, but I am specifically focused on an output that presents 2 directives: an APL and an APLA render document. My component is set up to handle this in the following way: @Handle({ global: true, prioritiz ...

Switching from a Promise to an Observable using React-Redux and TypeScript

I am struggling to grasp the concept of storing a Promise response into Redux. I believe finding a solution to this issue would greatly benefit me. Currently, I am utilizing a library that returns a Promise, and I wish to save this response - whether it i ...

The type '{ }' does not include the properties 'params', 'isExact', 'path', 'url' from the 'match<Identifiable>' type

Currently, I am utilizing react router and typescript in order to extract the id variable from a route for use in a component. However, typescript is raising an issue: The type '{}' lacks the following properties found in type 'match' ...

Angular mistakenly redirects to the local host at port 4200 with a hash symbol

After using this.router.navigate(['newcard']);, the URL loads correctly but then quickly redirects to localhost:4200/#. This is how I am redirecting from the showcard component to the newcard component: <a href="#" class="btn b ...

Ways to dynamically access input errors

Exploring My Implementation I have devised a function that takes an argument to access specific formik errors dynamically. This requires using bracket notation instead of dot notation as shown below: import {useFormikContext} from 'formik'; fun ...

How can we dynamically update a type in Typescript based on the existence of a particular property after filtering?

My array contains the following information: const list: Readonly<ListProps> = {some values} interface ListProps { type: 'radio' | 'check'; style: 'text' | 'button'; options: OptionProps[]; } interface ...

Protecting AWS Cognito User Pool and Client ID in a static webpage

According to the documentation from AWS (User Pool App Settings): Developers are responsible for securing app client IDs and secrets to ensure only authorized client apps have access to unauthenticated APIs. Is there a method to authenticate in a secur ...

MD-List Equilibrium Elevation

Seeking a solution for implementing a simple chat using the md-list template. The issue arises when new items are added to the md-list, causing it to expand. Desiring the list to behave similarly to other chat platforms, where the height remains constant ...

Generate dynamic forms utilizing JSON data

I am in the process of developing an application that enables users to answer questions about themselves. The questions are being retrieved from an API. My next step is to generate a form with these questions as entry fields. I am currently utilizing a met ...