Creating a fresh ngx-translate pipeline (comparing pure and impure methods)

Edit: I am looking to enhance the functionality of ngx-translate's pipe by extending it. Here is an example of how I achieved this:

import { Pipe, PipeTransform } from '@angular/core';
import { TranslatePipe } from "@ngx-translate/core";

@Pipe({
  name: 'msg'
})

export class MsgPipe extends TranslatePipe implements PipeTransform {
  transform(value: any, args: any[]): any {
    return super.transform(value, args)
  }
}

It seems that this only works when the pure property is set to false. It appears that the loader for ngx-translate may not be fully prepared yet. Is there a way to verify this? If so, I could maintain the purity of the pipe while ensuring its functionality.

Original post (not relevant):

I have developed a pipe that simply utilizes translateService.instant and outputs the result.

@Pipe({
  name: 'msg',
  pure: false
})
export class MsgPipe implements PipeTransform {

  constructor(private translateService: TranslateService) {}

  transform(value: any, args: any[]): any {
    console.log('checked. val = ', value)
    return this.translateService.instant(value, args);
  }
}

If I do not mark this as pure: false, the pipe only returns the initial value. By setting it, the desired outcome is achieved (assuming the file loader has been completed).

My concern is that each pipe call results in approximately 8 executions. Is there a way to optimize change detection to indicate to the pipe to cease checking once the value has been obtained?

Answer №1

If you are facing the issue of being triggered multiple times, a pure pipe can be a solution as it only triggers again when the input reference changes (1). However, the downside of using the translate service instantly is that the translation may not be available at the time of loading, making a pure pipe ineffective.

Fortunately, ngx-translate provides a pre-built pipe called the translate pipe (2) which can be utilized for this purpose.

It seems that there is limited control over preventing a pipe from re-evaluating itself. To address this, consider setting your component to OnPush mode so it updates only when its inputs change.

(1) https://angular.io/guide/pipes#pure-and-impure-pipes

(2) https://github.com/ngx-translate/core/blob/master/src/translate.pipe.ts

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

What could be causing TypeScript to throw errors when attempting to utilize refs in React?

Currently, I am utilizing the ref to implement animations on scroll. const foo = () => { if (!ref.current) return; const rect = ref.current.getBoundingClientRect(); setAnimClass( rect.top >= 0 && rect.bottom <= window.i ...

Template literal types in TypeScript and Visual Studio Code: An unbeatable duo

I'm encountering an issue while attempting to utilize literal types in Visual Studio Code. When following the example from the documentation, https://i.stack.imgur.com/V6njl.png eslint is flagging an error in the code (Parsing error: Type expected.e ...

Angular: undefined value detected during NgOnInit execution

Although the topic has been discussed, I am unable to find a solution to my specific issue. The problem lies in my parent component that returns data passed to an input. Parent component TypeScript: public productList!: IDocumentProduct[]; constructo ...

Issues with relocating function during the NgOnInit lifecycle hook in an Angular 2 application

Currently, I am facing an issue with my Angular 2 app where the data sometimes lags in populating, causing a page component to load before the information is ready to display. When this happens, I can manually refresh the page for the data to appear correc ...

Utilizing a function from a library in an Object within a Typescript environment

Currently, I am working on assigning a field within my interface to a function from an external library in the following manner: import { Accelerometer, } from 'expo-sensors'; type SensorInterface = { permChecker: () => Promise<Permiss ...

What is the method to determine the length of a string with TypeScript?

Looking to derive the numerical length of a string: type Length = LengthOfString<"hello"> // ^? should equal 5 Feeling a bit lost on how to approach this. Any guidance on how to achieve this? (Currently diving into typescript's typ ...

Unclear on the usage of "this" in arrow functions?

After going through various discussions and articles on this topic, I find myself still perplexed about the meaning of this in arrow functions. I've been encountering run-time errors with a code snippet similar to the following: export class Foo imp ...

You cannot directly access an array useState by index in React js, but you can use the map function to

export interface JobListing { id: number, isTraded: boolean, feedback: string, title: string, message: string, skills: string[], sender: string, ipAddress: string } const GroupList = () => { const [jobListings, setJobListings] = useSt ...

Leverage Typescript to convert string literal types to uppercase

type x = 'first' | 'second' I am looking to create a type y that is similar to this: type y = 'FIRST' | 'SECOND' Here is what I attempted: type x = 'first' | 'second' type y = {[key in x]: key[& ...

Limiting the number of characters in a textarea using React with TypeScript

Having encountered two issues, I've developed a textarea component that not only allows users to input text but also keeps track of the number of characters they have typed. First Issue: I'm attempting to check if the length of the current input ...

Unable to load Angular 2 Tour of Heroes application due to Typescript issue

My Angular 2 Tour of Heroes app seems to be stuck on the "Loading..." screen and I can't seem to figure out why. The angular-cli isn't showing any errors either. I'm currently at part five of the tutorial and it's becoming quite frustra ...

How can I resolve a route error after converting typescript to es5 in an Angular2 example?

I'm currently diving into the world of Angular2 and exploring how to convert TypeScript to ES5. You can find detailed instructions in this documentation: https://angular.io/docs/ts/latest/tutorial/toh-pt5.html Upon running the ES5 code, I encountered ...

Using an object hierarchy in Typescript to create an if statement

Currently, I am attempting to create a logical statement using a hierarchy structure as shown below: if ((config.elementConfig.curve[0].dataset[0].splitBy = 'my discrete var')) {..... However, when implementing this statement, I encounter the er ...

Disruptions in typing occur due to errors popping up while utilizing zod and react-hook-forms within a TypeScript application

Currently, I am working on developing a registration page for users using react-hook-forms for the registration form and zod for validation. Initially, when testing the form, I noticed that errors only appeared after submitting the form. However, once the ...

Encountering an issue saving files in Angular 2 when the npm server is active

Encountering an issue when trying to save .ts or .html files while npm is running 1: DoJoin(aka DoJoin) [native array.js:~129] [pc=0000035BB365DBB2] (this=0000005A3F604381 <undefined>,w=000003CB8840CFF1 <JS Array[104]>,x=104,N=0000005A3F6 ...

Every time I clear the information, it seems to be instantly replaced with new data. How can I prevent it from constantly refilling?

When I press the remove button on my application, it successfully deletes the data in a field. However, it also automatically adds new data to the field which was not intended. I am seeking assistance on how to keep those fields empty after removing the ...

Typescript iterative declaration merging

My current project involves creating a redux-like library using TypeScript. Here is an example of the basic action structure: interface ActionBase { type: string; payload: any; } To customize actions for different types, I extend the base interface. ...

Unlock the mat-sidenav from mat-dialog or @component in Angular Material

I have been exploring various options for a while now in search of a solution, so any assistance would be greatly appreciated. Currently, I am utilizing Angular Material 2 and I am looking to utilize the .open() method for a mat-sidenav by either pressing ...

Software designed for the web that utilizes both frontend and backend technologies, including JavaScript

Currently, I am collaborating on a project for a company that created software using Delphi. The software primarily featured a minimalist browser as its central component. This browser was used to analyze webpages, recognize patterns, save data, and more. ...

Tips for extracting specific information from a nested object in MongoDB

I am currently storing data for a NestJs based web application in MongoDB. My MongoDB data has the following structure: "gameId": "1a2b3c4d5e" "rounds": [ { "matches": [ { "match_id& ...