Utilizing Angular 2's pipe functionality with dynamic parameters

Currently I am diving into Angular2/Ionic2 and trying to grasp the concept of Pipes. Everything was going smoothly until I faced a roadblock in the form of a specific problem related to temperatures.

Let me illustrate my issue with an example involving temperature conversions between Celsius and Fahrenheit.

Suppose I have a custom Pipe that returns either Celsius or Fahrenheit temperature values, based on the user's setting stored in localStorage (Celsius being the default input value).

To tackle this, I created the following Pipe:

export class TemperatureConverterPipe implements PipeTransform {

  // Selected temperature unit
  private unit: string;

  constructor(private settings: Settings){
    // Fetch the temperature unit from localStorage immediately
    // And listen for changes
    this.settings.radio().subscribe(data => {
      this.unit = data.temp_unit
    });
  }

  // Convert temperature based on chosen unit
  transform(value: number): number {
    switch(this.unit){
      case "c":
        return value;
        break;
      case "f":
        return celsiusToFahrenheit(value);
        break;
      default:
       return value;
    }
  }

  // Function to convert celsius to fahrenheit
  celsiusToFahrenheit(value: number){
     return value * 9/5 + 32;
  }

}

The two main issues I am grappling with are:

  1. How can this Pipe monitor changes in parameters (temperature unit) and update the output accordingly (e.g., switching from C to F)? Currently, it only detects input changes (temperature value).
  2. Is this the correct approach to address this scenario?

Your insights and assistance are greatly appreciated!

Answer №1

Temperature Converter:

 @Pipe(name: 'tempConverter')
 export class TemperatureConverterPipe implements PipeTransform {

      // Define temperature converter pipe functionality here

      constructor(){

      }

      // Transform the temperature value based on selected unit
      transform(value: number,unit:string): number {
        switch(unit){
          case "c":
            return value;
            break;
          case "f":
            return celsiusToFahrenheit(value);
            break;
          default:
           return value;
        }
      }

      // Convert celsius temp to fahrenheit
      celsiusToFahrenheit(value: number){
         return value * 9/5 + 32;
      }

    }

HTML usage:

[temperatureProperty]="value | tempConverter:unit"

To use this temperature converter pipe, subscribe to the service in the ngOninit of calling component and pass the desired unit.

Answer №2

One way to modify the pipe is by making it impure.

@Pipe(name: 'tempConvert', pure: false)
export class TemperatureConverterPipe ...

By doing this, the pipe will be executed every time change detection is triggered. However, it's important to note that impure pipes should not perform any resource-intensive operations since they will be called frequently.

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 is the best way to communicate an event occurring within the ng-content to the reusable parent component in Angular?

I am looking to create a versatile dropdown component in Angular that can display different content such as a list or a tree. Essentially, I want to be able to extract the selection label that triggers the dropdown to open and close upon clicking. dropdow ...

unable to locate the nested routes in the folder for remix

Hey there, I've been using the remix to create a basic page and I'm trying to organize the routes using folders. Here is my project directory: - app/ - root.tsx - examples/ - route.tsx - child1/ - account.tsx In the examples di ...

How to utilize Enzyme to call a React prop in TypeScript

I'm currently in the process of converting my Jest tests from Enzyme to TypeScript, and I've come across a specific case that I'm unsure how to resolve. Essentially, I'm attempting to invoke a function passed as a prop to a sub-componen ...

The 'asObservable' property is not present on the type '() => any'.ts(2339)

Error: Property 'asObservable' does not exist on type '() => any'.ts(2339) Error: Property 'subscribe' does not exist on type 'Subscription'. Did you mean 'unsubscribe'?ts(2551) Error: Property 'sub ...

When utilizing ng2-bootstrap, there is no directive that is defined with the "exportAs" attribute set to "bs-modal"

I found a tutorial that I am trying to emulate from this website However, when I insert the template into my HTML file <div class="modal fade" bsModal #staticModal="bs-modal" [config]="{backdrop: 'static'}" tabindex="-1" role="dialog" ...

Extracting the hour and minute from a timestamp like 11:15 AM can be done using specific methods

I am trying to extract the hour and minute from a given time For instance: Time "11:56 PM" What I need is to separate the Hour - 11, Minute - 56, and AMPM - PM from the time. Can someone guide me on how to achieve this in Angular 6? Appreciate your he ...

The exportAs attribute is not specified as "ngForm" for any directive

Encountered an error while attempting to test the LoginComponent PhantomJS 2.1.1 (Linux 0.0.0): Executed 3 of 55 (1 FAILED) (0 secs / 0.307 secs) PhantomJS 2.1.1 (Linux 0.0.0) LoginComponent should create FAILED Failed: Uncaught (in promise): Error: Templ ...

Two separate menus for each root file in Ionic 2

In my Ionic 2 project, I have developed two root files: app.component and report-menu. In order to make the report-menu module accessible in the app.component.module.ts file, I imported it successfully. However, I am facing an issue where one menu is dis ...

How to Properly Convert a Fetch Promise into an Observable in Ionic 5 using Typescript?

I'm in the process of transitioning my Ionic3 app to Ionic5 and currently working on integrating my http requests. I previously utilized angular/http in Ionic3, but it appears that it has been deprecated. This was how I handled observables in my code: ...

"Utilize Tuple in TypeScript to achieve high performance programming

I've been delving into TypeScript, focusing on the tuple type. As per information from the documentation, here is the definition of a tuple: A tuple type is another form of Array type that precisely knows its element count and types at specific posi ...

Tips on managing the issue of "Preflight request response does not meet access control requirements: 'Access-Control-Allow-Credentials' value"

I am attempting to send an HTTP POST request to a web-api2 server running on my localhost. My client is operating on http://localhost:4200, and my server is running on http://localhost/MemoryGameServer/api/Test (Different Origin). Below is my Angular 7 cl ...

The shop named 'someStore' is currently unavailable! Please ensure that it is being offered by a valid Provider

I'm having trouble setting up a new project using React, Typescript, and MobX. Despite having a relatively simple piece of code, I can't seem to get MobX to work properly. It keeps showing me this error message: Uncaught Error: MobX injector: S ...

Creating routes with dynamic components or importing dynamic components in Angular 2 is a versatile and powerful feature

Is there a way to dynamically create routes or import components based on data? For instance, suppose I have a JSON file with objects containing RouteNames, paths, and ComponentNames. How can I dynamically generate route definitions from this data? The ch ...

Is it feasible to tailor the structure of the new application directory?

Recently, I was assigned a task to explore customizing the folder structure for new apps, specifically Nest apps. After some research, I discovered that it is possible to create a "lib" folder within the "tools" directory and leverage patterns to automatic ...

Error: Unable to execute this.threadData.pipe function - Unit Testing Angular 6 with JASMIN KARMA

Currently, I am in the process of writing unit test cases for an Angular 6 component. Despite achieving a code coverage of 65%, I have encountered an error within the following code snippet that has been quite bothersome to me. Specifically, I am unsure of ...

Exploring NextJS with Typescript

Struggling to incorporate Typescript with NextJS has been a challenge, especially when it comes to destructured parameters in getInitialProps and defining the type of page functions. Take for example my _app.tsx: import { ThemeProvider } from 'styled ...

There are zero assumptions to be made in Spec - Jasmine analyzing the callback function

I've encountered a challenge with a method that is triggered by a d3 timer. Each time the method runs, it emits an object containing several values. One of these values is meant to increase gradually over time. My goal is to create a test to verify wh ...

Empty initial value of a number type input element in React using TSX

In the process of developing a react POS app using Typescript, I encountered an issue with calculating change when entering the amount of money received from a buyer. The problem arises when the first value passed to the change calculation logic is empty, ...

React Quill editor fails to render properly in React project

In the process of developing an application in Ionic React, I am in need of a rich text editor that can save data on Firestore. Despite initializing the editor as shown below and adding it to the homepage component, it is not rendering correctly although i ...

How can I stop TypeScript from causing my builds to fail in Next.js?

Encountering numerous type errors when executing yarn next build, such as: Type error: Property 'href' does not exist on type '{ name: string; }'. This issue leads to the failure of my build process. Is there a specific command I can ...