Is there a way to modify the style within a TS-File?

I've created a service to define different colors and now I want to set separate backgrounds for my columns. However, using the <th> tag doesn't work because both columns immediately get the same color.

Here's my code:

color-variation-service

export class ColorVariationService {

  public defaultStyles = {
    firstBackgroundColor: '#25a1b1',
    secondBackgroundColor: '#c3c0c0',
  };

  sharedStyleSource = new ReplaySubject<any>(1);
  public sharedStyle = this.sharedStyleSource.asObservable();

  constructor() { }

  newStyle(obj: any) {
    this.defaultStyles[obj.name] = obj.value;
    console.log('defaultStyles:', this.defaultStyles);
    this.sharedStyleSource.next(obj);
  }
}

my-component

public myArray = [
    { attribute: 'firstColumn', name: 'Firstname'},
    { attribute: 'secondColumn', name: 'Lastname'},
  ];

ngAfterViewInit() {
    changeFirst('firstColumn');
    changeSecond('secondColumn');
  }

public changeFirst(attributeToChange: any) {
    const displayedColumn = this.displayedColumns.find((dc) => dc.attribute === attributeToChange);
    if (displayedColumn && displayedColumn !== null) {
      displayedColumn.attribute = this.colorVariationService.defaultStyles.firstBackgroundColor;
    }
  }

public changeSecond(attributeToChange: any) {
    const displayedColumn = this.displayedColumns.find((dc) => dc.attribute === attributeToChange);
    if (displayedColumn && displayedColumn !== null) {
      displayedColumn.attribute = this.colorVariationService.defaultStyles.secondBackgroundColor;
    }
  }

This approach doesn't seem to be working as expected. Can you suggest a solution to this issue?

Answer №1

My solution doesn't involve using your service.

I've created a method called changeColor() which takes a parameter. This parameter is the index of the tables-output (in my example, the index from the alphabet array). The changeColor() method checks against the index to determine if it's even (return color-one) or odd (return color-two) in order to alternate colors each time.

The color can be specified in the .ts file.

public changeColor(index: number): string {
  if (index % 2 == 0 ) { // if is even
    return "#25a1b1"; // first color
  } else if (index % 2 == 1 ) { // if is odd
    return "#c3c0c0"; // second color
  } 
}

In the HTML file, I set the background-color as follows and use the changeColor() method to choose one of the two colors:

<tr *ngFor="let element of alphabet; index as i">
    <td style="background-color:{{ changeColor(i) }};"> {{ element.name }} </td>
</tr>

You can view the implementation on my stackblitz

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

Encountering a Component Exception error in React Native while attempting to implement a Victory chart component

Currently, I am exploring the Victory library for react native to create a line chart for my budgeting application. Below is the code snippet from my Graph component: import React from 'react'; import { View, StyleSheet } from 'react-native& ...

What is the process for passing an object in the http.send() method?

I'm currently working on sending a POST request to a specific URL using the code below. However, when passing an object to the http.send(params) function, it's resulting in a (400) bad request error. I'm having trouble pinpointing the issue ...

What is the proper way to utilize a class with conditional export within the Angular app.module?

This query marks the initiation of the narrative for those seeking a deeper understanding. In an attempt to incorporate this class into app.module: import { Injectable } from '@angular/core'; import { KeycloakService } from 'keycloak-angul ...

JavaScript: Receiving an error that function is undefined when working with data binding

Why is my code showing that it's not defined while I'm attempting a simple code with data binding? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="ht ...

Seeking particular section of online content in an asynchronous manner

Is there a method for asynchronously requesting a specific portion of a web resource (like the initial 100 bytes) using JavaScript? I believed this could be accomplished through XmlHttpRequest by adjusting its Range header. However, if the server utilizes ...

The Correct Way to Implement Return in jQuery Ajax

Encountering an issue with the login form where I am unable to proceed to the next page after entering my credentials. The system acknowledges if the email and password match, however, the login does not go through. Seeking assistance in identifying the ...

transferring data from JavaScript to PHP variables

Currently, I am working on a project that involves using ajax to access the database asynchronously. The value retrieved is stored in a JavaScript variable like this: var content=xmlhttp.responseText; My next step is to pass this value to the PHP module ...

Restrict the number of rows in a CSS grid

Hello there, I am in the process of creating an image gallery using CSS grid. Specifically, my goal is to initially show just one row of images and then allow users to click a "Show more" button to reveal additional images. You can see my progress here: ...

What sets the do/tap operator apart from other observable operators?

Can anyone clarify the distinction in simple terms between the typical observable operators used for observing output and why do/tap appear to serve the same purpose? What is the reason for utilizing do/tap? ...

The map component does not render when the agm-map is placed within the component

Objective I am attempting to encapsulate an <agm-map> within my custom <app-map> component, but it is not appearing in the HTML output. The agm (angular google maps) library is properly configured and the map displays correctly when the <a ...

Unit Testing in Vue.JS: The original function remains active even after using sinon.stub()

While unit testing my components (which are coded using TypeScript along with vue-class-component), I am utilizing Sinon to stub API calls. However, even after adding the stub to the test, the original method is still being invoked instead of returning the ...

Using TypeScript to filter and compare two arrays based on a specific condition

Can someone help me with filtering certain attributes using another array? If a condition is met, I would like to return other attributes. Here's an example: Array1 = [{offenceCode: 'JLN14', offenceDesc:'Speeding'}] Array2 = [{id ...

serving files using express.static

I have set up express.static to serve multiple static files: app.use("/assets", express.static(process.cwd() + "/build/assets")); Most of the time, it works as expected. However, in certain cases (especially when downloading many files at once), some fil ...

The display of the selected input is not appearing when the map function is utilized

I am attempting to use Material UI Select, but it is not functioning as expected. When I use the map function, the default value is not displayed as I would like it to be. However, it does work properly when using the traditional method. *** The Method th ...

Challenges with loading times in extensive AngularJS applications

We are currently tackling performance issues related to the loading time of our AngularJS application. The page takes a significant amount of time to load, and we are exploring potential causes for this delay. One factor that could be contributing to the ...

Determining the Similarity of jQuery Selectors' Selected Elements

I'm looking for a way to programmatically identify if two jQuery selectors have chosen the exact same element. My goal is to iterate over multiple divs and exclude one of them. This is what I envision: var $rows, $row, $row_to_exclude; $rows ...

Alter the style type of a Next.js element dynamically

I am currently working on dynamically changing the color of an element based on the result of a function //Sample function if ("123".includes("5")) { color = "boldOrange" } else { let color = "boldGreen" } Within my CSS, I have two clas ...

Implement the anti-flickering script for Google Optimize in a NextJS/ReactJS environment

While working on a NextJS/ReactJS project, I am experimenting with setting up Google Optimize for some tests. One issue I have encountered is the flickering effect that occurs when Optimize changes visual elements during experiments. To address this probl ...

Removing an event from Fullcalendar

With the help of a post on StackOverflow, I managed to modify my select: method to prevent users from adding an event on a date before NOW. However, there is a drawback. When a user clicks on an empty time slot and the system displays an alert message, th ...

Highcharts real-time data not refreshing following modification of PHP variable

Currently, I have a live updating highchart implemented on a webpage named index.html. This highchart calls a PHP script called datatest.php to parse a CSV file, convert the data into JSON format, and then add it as a new point on the chart: $.ajax({ ...