Customizing Ng2-smart-table cell background color based on the content

I've been experimenting with Ng2-smart-table module (link: ).

Wondering if it's possible to personalize the background of a cell or entire row based on the content of that cell or another cell in the same row. Any chance you could show me an example?

Appreciate your help!

Answer â„–1

To add a dynamic touch to the style, I opted for using a variable that changes according to the situation. In my specific scenario, I needed to apply a background color depending on the type of fuel being used. Here's how I implemented it:

 Volume: {
    type: 'html',
    title: 'Volume',
    valuePrepareFunction: ((Volume, row)=> {
        return this.domSanitizer.bypassSecurityTrustHtml(`<h6 class="text-white p-t-0 qlz-line-height text-center" style="background:${this.getFuelColor(row.FuelType)}"><strong>${Volume} gal </strong> < /h6>`);
    }),
    width: '15%'
  }

In the getFuelColor(fuelType) function, I compute the color based on the specific fuelType.

Answer â„–2

I have discovered the solution:

import { Component, Input, OnInit } from '@angular/core';
import { ViewCell } from 'ng2-smart-table';

@Component({
  template: `
  <span [ngClass]="classToApply">{{renderValue}}</span>
  `,
  styles: ['.error { color: red; }']
})
export class CustomColumnRenderer implements ViewCell, OnInit {

  renderValue: string;

  @Input() value: string | number;
  @Input() rowData: any;

  classToApply = '';

  ngOnInit() {
    if(this.value == 'MY_ERROR_CODE') {
      this.classToApply = 'error';
    }
    this.renderValue = this.value.toString().toUpperCase();
  }

}

Answer â„–3

If you simply want to modify the class based on a cell value, you can use the valuePrepareFunction :

valuePrepareFunction: (cell) => {
  if (cell === 'one') {
    return '<p class="firstCellClass">' + cell + '</p>';
  } else if (row.anotherCellName == 'two') {
    return '<p class="secondCellClass">' + cell + '</p>';
  } else {
    return '<p class="defaultCellClass">' + cell + '</p>';
  }
},

There is also a rowClassFunction available for styling the entire row:

https://github.com/akveo/ng2-smart-table/pull/355


Using a custom render component can be beneficial when you need to apply specific CSS styles that are not supported within an 'html' cell type.

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

Utilizing BullMQ in Combination with NestJS for Queue Name Management

Currently, I am in the process of developing an application with BullMQ and NestJS. Everything seems to be working smoothly, but there is a particular issue that is bothering me. Whenever I register a new queue within my application, I typically follow th ...

Encountering a JavaScript/TypeScript issue that reads "Unable to access property 'Items' as it is undefined"

I encountered an issue with Javascript where I'm receiving an error message stating "Cannot read property 'Items' of undefined". The this keyword is consistently showing as undefined in the Base class. How can this problem be resolved? Coul ...

Encountering a 404 error in Angular 9 when refreshing the browser

Encountering a 404 error when attempting to access mysite.com/menu directly, but no issues when navigating through the homepage and selecting the menu option. Tried implementing an .htaccess file following Angular documentation, yet problem persists. Cur ...

How can we declare React context functions to avoid any potential linting problems?

Working with React Context, I currently have: const DocumentContext = createContext< [DocumentStateType, React.Dispatch<any>, React.Dispatch<any>] >([initVal, () => { }, () => { }]); However, I am receiving a complaint from my ...

Creating a moving button using React when the state changes

I am attempting to create a button that animates a label when a certain event occurs, such as onclick or an HTTP success/error response. However, I am struggling to apply the appropriate classes and find an elegant way to manage this through the component ...

When deployed, Angular 14 and Bootsrap 5 are functioning properly on a local environment but encountering issues on an online

My Angular application (version 14.2.0) is integrated with bootstrap (version 5.2.3). Upon building and deploying the application on a local IIS server, everything displays correctly as shown in the image below: https://i.sstatic.net/pLDs6.jpg However, w ...

Is it necessary to include @types/ before each dependency in react native?

I am interested in converting my current react native application to use typescript. The instructions mention uninstalling existing dependencies and adding new ones, like so: yarn add --dev @types/jest @types/react @types/react-native @types/react-test- ...

Issue with using useState inside alert: unexpected empty array

I am facing an issue with the 'exercises' useState in my code. The useEffect function correctly prints the 'exercises' after every change, but when I press the 'Finish' button, the 'exercises' suddenly become empty. ...

Utilize Javascript to compare nested objects and store the differences in a separate object

I have a dilemma involving two JavaScript objects var order1 = { sandwich: 'tuna', chips: true, drink: 'soda', order: 1, toppings: [{VendorNumber: 18, PreferredFlag: false, SupportedFlag: true}, {VendorNumber: 19, ...

Capturing a center mouse click event in a directive for Angular 6

I created a unique custom directive where I aim to capture middle mouse button click events. Initially, I thought it would be a straightforward process by setting the normal click event and working from there. However, I noticed that it only triggers when ...

Access custom IDs in Angular FormArrays to retrieve specific FormControls

I'm having trouble setting the formControlName of a formArray and connecting it to an input field. Form: this.translationForm = new FormGroup({ translations: new FormArray([]), }); this.translations.push( new FormControl({ de: '' }, [ ...

How can you selectively export a single function from a JavaScript file?

Within my project, I have two separate modules - one written in ts and the other in js. There is a utility within the js module that needs to be accessed by the ts module. The utility service.js looks like this: module.exports = { helloFriends: functi ...

TypeScript properties for styled input component

As I venture into TS, I’ve been tasked with transitioning an existing JS code base to TS. One of the challenges I encountered involves a styled component in a file named style.js. import styled from "styled-components"; export const Container ...

Update a BehaviourSubject's value using an Observable

Exploring options for improving this code: This is currently how I handle the observable data: this.observable$.pipe(take(1)).subscribe((observableValue) => { this.behaviourSubject$.next(observableValue); }); When I say improve, I mean finding a wa ...

Setting the default value to null or 0 in a Select dropdown in Angular 7

There is a select dropdown code that may be hidden in some instances. When the select dropdown is hidden, I want to ensure null or 0 is sent instead of an empty value when saving the form. How can I achieve this? <div class="col-md-4" [hidden]="!cpSe ...

Enhance autocomplete functionality by incorporating a left icon feature for text fields within the autocomplete component

I have a component with autocomplete functionality that displays tags Autocomplete with tags and I am trying to add a left icon, but only the right icon is functioning correctly. Current Issue When I add a left icon, it shows up but prevents the renderi ...

What is the best way to execute an Nx executor function using Node.js?

Can a customized Nx executor function be executed after the app image is built? This is the approach I am taking: "migrate-up": { "executor": "@nx-mongo-migrate/mongo-migrate:up", "options": { &q ...

Detecting changes in Angular custom form controls when using `mat-select` with the `selectionChange` event

I'm facing an issue with my custom form control that includes a mat-select element I've been attempting to listen for the change event in the parent component However, my onTouchedCallback doesn't seem to be functioning for some reason Wh ...

Accessing enum values in a view with Typescript and AngularJS version 1.5

Recently started working with Angular 1.5 and Typescript I have a service that returns data in an array format called devices.headerEntries: [{name:id,value:45} ,{name:Mode,value:1},{name:State,value:2},{name:serialnum,value:123434} I created a componen ...

Exploring the capabilities of the Next.js router and the useRouter

import { routeHandler } from "next/client"; import { useRouteNavigator } from "next/router"; const CustomComponent = () => { const routerFromHook = useRouteNavigator(); } export default CustomComponent; Can you explain the disti ...