Update each number in an array by appending a string within a table in an Angular component, rather than the

I have created a function that decides on a comment based on the result number added to an array and displays it in a table.

However, calling this function within the template is causing a performance slowdown. Is there a way to achieve the same outcome without directly calling the comment() function in the HTML code?

Here is the StackBlitz project

To use the dropdown, simply click inside the input field and type either "F" for Fahrenheit or "C" for Celsius.

The process involves saving the results to the Local Storage and adding new results to an array (history of calculations).

Even though I dislike calling this function directly in the HTML, I am struggling to find an alternative implementation within the component itself.

        <td>{{ comment(history.result, history.temperatureUnit === 'C') }}</td>

Answer №1

Create a personalized pipe:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'commentResolver'
})
export class CommentResolverPipe implements PipeTransform {

  transform(temperature: number, isCelsius: boolean): string {
    if (isCelsius) {
      temperature = (temperature * 9) / 5 + 32;
    }
    
    if (temperature >= 75 && temperature <= 90) {
      return 'Caution: fatigue is possible with prolonged exposure and activity. Continuing activity could result in heat cramps.';
    } else if (temperature > 90 && temperature <= 105) {
      return 'Extreme caution: heat cramps and heat exhaustion are possible. Continuing activity could result in heat stroke.';
    } else if (temperature > 105 && temperature <= 130) {
      return 'Danger: heat cramps and heat exhaustion are likely; heat stroke is probable with continued activity.';
    } else {
      return 'Extreme danger: heat stroke is imminent.';
    }
  }

}

Implement it as follows:

<td>{{ history.result | commentResolver: history.temperatureUnit === 'C' }}</td>

Access Stackblitz example here

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 a way to send my form data to a different URL once it has been submitted?

In the form I am designing, customer-related information needs to be filled out. There are three tasks that I am trying to accomplish with this form: 1. Validate the information such as correct email address and mobile number. 2. Post the form data in ...

Ensuring the safety of ajax GET/POST communication between client and server

Let's say I'm working with a specific API and my file server.php is responsible for connecting to the API service. On the client side, I am using an AJAX call like this: $http({ url : 'server/server.php', method : &ap ...

Discovering the following solution in JavaScript

I am a beginner in the field of web development and seeking help in generating a specific output for a given problem: var totalRows = 5; var result = ''; for (var i = 1; i <= totalRows; i++) { for (var j = 1; j <= i; j++) { res ...

Is there a way to make an HTML link target the same as JavaScript window.opener?

Within my project, the main page is where users log in and access the primary tables. Additionally, there are numerous supplementary pages that open in separate windows. Once the login session times out, it is essential to restrict user access to any cont ...

Getting the search bar's result set and simultaneously wiping out the existing data

If we input the value 5, a result set is displayed if there is a match. However, entering 56 results in an error message stating "no data found". The issue arises when clearing the first value 6, causing the function to no longer search for the input 5. ...

Despite my usage of className, I still encounter the error message "Error: Invalid DOM property `class`."

I am having trouble debugging this issue as I am unsure of the exact location of the error. Here is the link to the repository: https://github.com/kstaver/React-Portfolio Error #2. There are three more promise rejection errors present, which I will addres ...

Looking for guidance on integrating cookies with express session? Keep in mind that connect.sid is expected to be phased out

Within my app.js file, I have the following code snippet: app.use(session({secret: 'mySecret', resave: false, saveUninitialized: false})); While this setup functions correctly, it triggers a warning message: The cookie “connect.sid” will ...

Why does routing function correctly in a browser with AngularUI Router and Ionic, but not in Ionic View?

My Ionic App runs smoothly in the browser when using ionic serve. However, I encounter issues with routing when running the app in Ionic View (view.ionic.io) after uploading it with ionic upload. The index.html loads but nothing within <div ui-view=""& ...

Preserving the button's state when clicked

Here is my code snippet: <blink> const [thisButtomSelected, setThisButtomSelected] = useState(false); var thisButton = []; const onAttributeClick = (e) => { thisButton[e.currentTarget.value] = { thisID: e.currentTarget.id, thisName: e. ...

The prop observation was activated without any alterations

Within my component, I have a prop X that I assign to data Y during the created hook. This setup allows me to easily modify Y without affecting X. Both X and Y are Arrays. Additionally, I've set up a watch on prop X to ensure Y is updated whenever X ...

Error in Ionic2 TypeScript: 'google' and '$' names not found, despite Google Maps and jQuery functioning correctly

I am currently working on developing an ionic2 application using TypeScript. Within the index.html file, I have attempted to integrate jquery and the Google Maps JS API before cordova.js: <!-- Vendor --> <script src="https://maps.googleapis. ...

Encountering a blank webpage displaying a warning that reads, "The use of 'event.returnValue' is outdated

Although this issue has been discussed before and was previously considered a bug, I am currently using jQuery v1.11.0, which should have resolved it. The problem I am encountering is that when my page loads, there is supposed to be a slide-in effect (as a ...

Change the color of the Parent Menu when a childMenu is clicked on using CSS and HTML

<li class="btn-group" mdbDropdown> <a mdbDropdownToggle id="ParentId"> <i class="nav-item"></i> MainMenu <i class="fa fa-angle-down"></i> </a> <div class=" ...

Trigger oncopy on the body excluding specific class

Is there a way to execute a function on document.body.oncopy but exclude a certain class (defined for div elements) from this function call? I want to avoid calling the function on specific classes, is there a method to achieve this? ...

What is the best way to save only the time in MySQL using Sequelize?

How can I properly store the Time HH:MM:SS using sequelize without encountering errors? I've tried using Time as a String and also as a Date Object, but I'm still facing issues. Here is the function I am using: const dateCollection = await booki ...

How to smoothly fade out content when hovering over a menu item in HTML<li> tags

Hi there, I have encountered a problem and could really use your assistance. I am attempting to create a menu that displays content when you hover over an li tag. The first content should always be visible when hovering over the first li option or if no l ...

Setting the button value to a textbox and refreshing the status information (Codeigniter)

How do I pass the value of my "ACTIVE" status attribute to my textbox? I want to update the user's status by clicking the ACTIVE button. The user's status is currently pending. While I can easily pass the userID, I'm facing an issu ...

Currently using Mongoose and Luxon to showcase the event date, however, I am encountering an issue where the displayed date is one day earlier than expected

Currently, I am working with Mongoose and Luxon to present a date chosen by the user from a form. However, there seems to be an issue where the date is being console logged as one day, but appearing on the page as the previous day. Below is my model setup ...

Troubleshooting: Mongoose Array Object Order Modification Issue

Imagine we have a person named Michael who lists his favoriteFruits as [ { name: 'Apple'}, {name: 'Banana'} ] The challenge at hand is to change the order of his favorite fruits. In other words, we want to transform it from: [ { name ...

The functionality of Angular router is disrupted when guards yield an Observable as their return value

My goal is to redirect users who are not logged in when they try to access protected routes, but I am facing an issue with redirection. The function that checks if the user is logged in returns an Observable. Below is the code snippet from my PrivateGuard ...