Modify color - Angular Pipe

I needed to make 2 transformations on my Angular template. The first transformation involved changing the direction of the arrow depending on whether the number was negative or positive. I achieved this using a custom Pipe.

The second transformation was to change the color of the number to red if it was negative, and green if it was positive.

Here is the custom Pipe I created for the arrows:

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

@Pipe({
  name: 'topBar'
})
export class TopBarPipe implements PipeTransform {

  transform(value: number): string {
    if(value < 0){
     return 'arrow_downward'
    }
    else if(value > 0){
      return  'arrow_upward'
    }
    return ''
  }

}

This is the HTML code calling the custom Pipe for the arrows:

 <mat-icon>{{
 qtdEvents.lastMonthMinusCurrentMonthQuantity | topBar
  }}</mat-icon>

The arrow transformation worked successfully, but I am unsure how to tackle changing the color of the number based on its sign. Would I need to use a Pipe for this as well?

Answer №1

You have the option to create a new pipe that changes color based on certain criteria:

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

@Pipe({
  name: 'colorChange'
})
export class ColorChangePipe implements PipeTransform {

  transform(value: number): string {
    if (value < 0) {
      return 'red';
    }
    return 'green';
  }
}

Then, apply the ngStyle directive to dynamically update the color of an element, such as a div:

<div [ngStyle]="{ 'color': exampleValue | colorChange }">
  {{ exampleValue | customPipe }}
</div>

Answer №2

Instead of creating a new pipe just for changing the color, you can simplify the process by using the code below:

<mat-icon [ngStyle]="{ color: (qtdEvents.lastMonthMinusCurrentMonthQuantity < 0) ? 'red' : 'green' }">
  {{ qtdEvents.lastMonthMinusCurrentMonthQuantity | topBar }}
</mat-icon>

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

Unique: "Unique styling for Ionic on emulator versus web localhost"

My perception of CSS codes in browsers versus emulators differs. I believe that currently, CSS codes only work properly in browsers. For instance, I attempted to change -ion-background-color for .md body and iosbody. However, the emulator still displays t ...

Enhance your coding experience with code completion and autocomplete in Angular/Typescript using ATOM within

Is it possible to have Codecompletion / Autocomplete in Atom similar to Webstorm? Currently I am getting familiar with TypeScript and really enjoying it, but the lack of Codecompletion support for my HTML files in Atom is quite frustrating. Having this f ...

Guide to aligning a component in the middle of the screen - Angular

As I delve into my project using Angular, I find myself unsure about the best approach to rendering a component within the main component. Check out the repository: https://github.com/jrsbaum/crud-angular See the demo here: Login credentials: Email: [e ...

Typescript objects may contain keys that are dependent on certain parameters

I have a challenge with constructing an object that requires querying multiple database tables, resulting in a time-consuming process. To address this issue, clients of the object need to specify which specific parts they require. For example, let's c ...

What is the correct way to access $auth in Nuxt with TypeScript?

<script lang="ts"> import LoginAdmin from '@/components/LoginAdmin.vue' import { Component, Vue } from 'nuxt-property-decorator' import Auth from "@nuxtjs/auth"; export default class MyStore extends Vue { pub ...

Having trouble loading static files in Django Angular framework? Specifically, images stored in the assets folder returning a

In my Angular project, I have an assets/image folder within the src directory where all my images are stored. Various components and child components in my app use these images like <img src"../../../assets/image/test.png">. After building my Angula ...

Tips for adjusting the width of ng2 smart table columns

Here is an example of my three columns, showcasing the ability to customize width sizes. modifyPassword: { title: this.gridTittle["Modify Password"], type: 'custom', renderComponent: UserPasswordChangeComponent, filter: false }, ...

What steps should I take to generate a compiler error when a variable is not of the type "never"?

Imagine having a set of conditions with different possible values and wanting to cover each potential case. In the event of adding a new condition in the future but forgetting to handle it, it is important to have an error detection mechanism—ideally cat ...

Exploring Angular RxJS: the art of filtering Observable arrays

Is there a way to effectively filter an array Observable in Angular? I am working with an observable Array: announcementList$: Observable<Announcement[]> = this.announcementService.getAnnouncement(0,0).pipe(filter(Boolean),shareReplay(), map(({data} ...

Angular 6: encountering difficulty in setting up component routes (from root to child) when creating separate modules

As a newcomer to Angular, I'm encountering some difficulties in defining child routes in Angular. I'm not sure where I'm going wrong. When I try to create a separate module for the child components, I run into issues when defining the routes ...

Unable to connect to localhost nodejs server from Windows browser when using WSL2

My computer runs on Windows 10 and has the Linux (Ubuntu-20.04) subsystem using WSL2. I've successfully initiated a frontend project (vue project) and running npm run serve works as expected with the application running on localhost:8080. However, whe ...

Is there a way to customize the default styles of Kendo UI for Angular?

Is it possible to customize the default datepicker styles to look like the design in the second image? https://i.sstatic.net/h8yfA.png https://i.sstatic.net/PfiSf.png ...

The .slice() function in TypeScript has the ability to alter the initial array

I am diving into TypeScript and just tackled my first slice() method. My understanding is that the slice() method is supposed to create a copy of an array. Here's a snippet of the code: class ChapterOne { // Gauss Jordan Elimination // No ...

What is the best way to utilize @Input in components that have been generated using ComponentFactoryResolver?

Is there a way to specify an @Input property for an Angular 2 component that is created dynamically? I am utilizing the ComponentFactoryResolver to generate components within a container component. For instance: let componentFactory = this.componentFacto ...

Ensuring Safe Definition of HTMLCollectionOf Elements in TypeScript with React

I'm currently working on creating a d3 line chart using react and typescript, and I'm using https://bl.ocks.org/larsenmtl/e3b8b7c2ca4787f77d78f58d41c3da91 as a reference for implementing the mouse over functionality. During one step of the proce ...

Determining if an item is empty, undefined, or null in Angular: a guide

I received a .json file structured as data [0 ... n]. Each position in the data array contains an object with various attributes, such as: {photo1, photo2, photo3 ... photoN} For a visual representation of how the json file is formatted, you can check ...

The current value of React.createRef() is perpetually empty

Ever since I started working on this code, I've been encountering a problem that seems to have no solution. Here's what's going on: import React, { Component } from 'react'; export class InfoPaneArrow extends Component<InfoPane ...

Navigating using Javascript library in Angular 2 framework

I am currently utilizing Parse, an external JS library, within Angular JS 2. Nevertheless, I am encountering issues when attempting to call the function gotoMain() from within a callback function of Parse. It appears that certain elements are not being l ...

Issue encountered with Angular 12 Material table: The data source provided does not match an array, Observable, or DataSource

When my REST API returns the following data: { "id": 1, "userId": 1, "date": "2020-03-02T00:00:02.000Z", "products": [ { "productId": 1, "quantity": 4 }, { "productId": 2, "quantity": 1 }, { "productId": 3, "quantity": 6 } ], "__v": 0 }, I attempt to imple ...

When working with an observable in an Angular Material table, the *ngIf directive may not function as expected

Attempting to utilize an Angular Material table with expandable rows, specifically to display information based on screen width reaching a particular breakpoint. Utilizing an observable isHandSetPortrait$ that is subscribed to in the HTML to determine if t ...