What is the process of creating Excel-like data bars using Angular?

I am seeking a way to incorporate databars behind the values in a specific column within my grid, similar to the Data Bars Conditional Formatting feature in Excel as shown here.

I came across an answer that demonstrates how to achieve this using jQuery data table. Can someone provide guidance on how to implement this in Angular 6?

Please note that I am not utilizing any third-party grids; I have developed this grid myself.

The desired outcome should resemble the following: https://i.sstatic.net/CmJt0.png

Answer №1

If you're unsure about when to use this, check out the following resource for creating CSS progress bars: https://css-tricks.com/css3-progress-bars/

This technique involves using HTML and CSS to create a customizable bar.

The concept is simple - you have a "wrapper" element that sets the maximum length, and a "bar" element inside it where you can define the width as a percentage along with a background color.

For example, here's how you could create a blue bar that is 50% wide:

.wrapper {
    width: 100%;
}

.bar {
    background: blue;
    height: 5px;
}

<div class="wrapper">
    <div class="bar" style="width: 50%"></div>
</div>

You can create an Angular component based on this idea by allowing the width to be passed in as a parameter. Here's an example:

import { Component, Input } from '@angular/core';

@Component({
    selector: 'app-bar',
    template: `
      <div class="wrapper">
          <div class="bar" [style.width]="width"></div>
      </div>
    `,
    styles: [`
    .wrapper {
        width: 100%;
    }
    .bar {
        background: blue;
        height: 5px;
    }
    `]
})

export class BarComponent {
    @Input() width: number;
}

Answer №2

Click here for the solution.

@Component({
  selector: 'my-app',
  template: `
  <div class="holder">
    <div class="bar" *ngFor="let item of data">
      <div #bar class="{{item >= 0 ? 'positive' : 'negative'}}">
        <div class="size" [style.width.px]="getWidth(item, bar)">
          {{item}}
        </div>
      </div>
    </div>
  </div>
  `
})
class AppComponent {  
  maxValue = 100;  
  data: Number[] = [
    10,20,30,-45,90,-90,-80,50,100
  ]

  getWidth(dataItem: number, bar: HTMLElement):number {
    return (parseInt(bar.offsetWidth) / this.maxValue)  * Math.abs(dataItem);
  }
}

CSS:

.holder {
  border: 1px solid black;
  margin: 10px;
  padding: 5px;
  width: 200px;
}

.bar {
  border: 1px solid grey;
  padding: 3px;
  margin: 10px 5px;
  text-align: center;
}

.positive {
  color: blue;
  width: 90px;
  margin-left: 90px;
}

.negative {
  color: red;
  width: 90px;
  margin-right: 90px;

  .size {
    margin-left: auto
  }
}

.size {
  background: green;
}

Answer №3

If you're looking to enhance the appearance of your data table, consider utilizing PrimeNg's cell formatting feature. This allows you to format each cell based on specific conditions, such as changing the color or adding a custom design. For more information, check out PrimeNg Cell Style.

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

"Implementing a unique constraint in Drizzle-orm PostgreSQL with the additional condition of deleted_at being

Is there a way to construct a table using a WHEN SQL tag? I am interested in setting up a table similar to this: "members_table", { id: serial("id").primaryKey(), email: text("email").notNull(), team_id: text(&q ...

There is no value stored in the Angular BehaviorSubject

My attempt at creating a web-socket-client involved organizing all server messages into a BehaviorSubject. Here's the snippet of code: export class WebSocketConnectionService { public ResponseList: BehaviorSubject<WebSocketResponse> = new Be ...

Using Angular 4 with Firebase to display nested objects within an object

My Firebase data: { "hotel" : { "-Kjgyamcup6ULm0Awa-1" : { "complete" : "true", "images" : { "-Kjgyb6A2gRiDhwaWx-V" : { "name" : "2.jpg", "url" : "https://firebasestorage.googleapi ...

Obtain the user's ID in string format from the clerk

I'm trying to retrieve the clerk ID to cross-reference with the backend. The issue is that the clerk is using a hook which isn't compatible with this function type. export const getServerSideProps = async ({ req }) => { const { isLoaded, is ...

The enum cannot be assigned a type of 'string | null'

Within my ProductGender enum, I have: enum ProductGender { Men, Women, } In my getProducts service: public getProducts( gender: ProductGender, category: ProductCategory ): Observable<IProductInterface[]> { return this.httpPro ...

"Encountering issues with running a MongoDB aggregate query involving date fields

I have been attempting to retrieve data from MongoDB using an aggregate query in Node.js for a specific date range. let date = '20230925' let year = date.slice(0, 4); let month = String(date.slice(4, 6)).padStart(2, '0'); ...

Enhance your AJAX requests with a retry mechanism when incorrect payloads are sent in subsequent requests

Currently, I am working with Angular and RXJS and facing an issue where I need to execute up to 5 AJAX requests concurrently. Each request should be attempted up to 3 times before giving up and returning an error. The problem I'm encountering is that ...

The 'Server' type is not designed to be generic

Out of nowhere, I encountered the following error: TypeScript: ./..\..\node_modules\@types\ws\index.d.ts:328:18 Type 'Server' is not generic. Angular CLI: 13.3.11 Node: 16.13.2 Package Manager: npm 8.1.2 OS: win3 ...

Angular - Error: Cannot read property 'publishLast' of undefined

My goal is to prevent multiple requests from being created when using the async pipe. I am facing an issue with a request to fetch a user from the API: getUser() { this._user = this.http.get<User>(environment.baseAPIUrl + 'user') ...

Using SCSS based on the browser language in Angular: A Step-by-Step Guide

Is there a way to implement SCSS that is dependent on the user's browser language? When I checked, I found the browser language specified in <html lang = "de"> and in the CSS code as html[Attributes Style] {-webkit-locale: "en&quo ...

Is it possible to utilize Typescript and Browserify in tandem?

As I explore the compatibility of TypeScript and Browserify, one perplexing aspect stands out - they both utilize 'require' but for different purposes. TypeScript uses 'require' to import other TS modules, while Browserify employs it to ...

Can the native script plugin background-http be used to upload an image file to an endpoint with the following properties:

Headers: Content-Type: application/x-www-form-urlencoded Authorization: token Body: Form-Data Key: "name" Value: image-file It seems a bit odd to me because usually application/x-www-form-urlencoded is used for toBase64String uploads, but here the endpoi ...

What is the best way to sequence asynchronous functions in Angular?

In my software, I have incorporated two essential services and functions: The first one: fetchData() { return this.http.post(this.base_URL + "web_app/login/", JSON.stringify(this.login)) .subscribe(response=>{ this.access_token = response ...

Ways to manage an rxjs observable reaction that may potentially have no data?

Currently, I am working with Angular2 and Ionic2 using typescript and have a requirement to manage responses from the backend service. The response may either be empty with http status 200 or it could be a json object containing an error message property ...

transferring information from the parent to the child in Angular 4

Having some inquiries, I kick off on page main.ts. Using onInit, I retrieve data from a mongoose database server and store it in an array. Now, this array needs to be accessible in other components. The approach I currently follow involves the use of a s ...

Angular 2 introduces one-way binding, which allows for modifications to be applied to both objects

How does one-way binding modify both objects? <component2 [obj]="obj1"></component2> Is there a way to make changes to obj without affecting obj1? It seems that only duplicating obj solves this issue. Is there another method in angular2 to a ...

Loading dynamic components asynchronously in Vue 3 allows for improved performance and enhanced user experience

My goal is to dynamically display components based on their type. Here's how I'm approaching it: I have several similar components that should show different content depending on their type. Using the defineAsyncComponent method, I can easily im ...

Track and log async routes for undefined values once await is complete

Currently facing challenges with multiple queries and synchronous code while writing an Express endpoint in TypeScript to update a user's password in the database. The issue I am encountering is that when attempting to await the return of a function, ...

Issue with Ant Design form validation

After reading through the documentation, I attempted to implement the code provided: Here is a basic example: import { Button, Form, Input } from "antd"; export default function App() { const [form] = Form.useForm(); return ( <Form f ...

The SSE `this.eventSource.onmessage` function is not working as expected. The error message states that the MIME type of EventSource's response is "application/json" instead of the required "text/event-stream"

An issue is occurring with the Angular Server Sent Event this.eventSource.onmessage call, resulting in an error message stating: "EventSource's response has a MIME type ("application/json") that is not "text/event-stream". Aborting the connection.". U ...