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

Unlocking new perspectives with a click

Currently exploring Angular development, I have encountered a question here but couldn't find the solution I was looking for. I am seeking suggestions and ideas on how to approach this issue. Essentially, my HTML includes buttons like the ones shown ...

PHP and Ajax Form Submission Directing to Backend PHP Script

While working on a portfolio, I encountered an issue with the contact form. When I click the submit button to send a message, instead of displaying the bootstrap alert message below the form, the page redirects to the PHP file. Although I receive the emai ...

Having trouble with Javascript/jQuery not functioning in IE8?

My current project involves a website that functions smoothly in Chrome, but encounters issues with running JavaScript/jQuery scripts in IE8. Even a simple alert on page load fails to execute. Admittedly, my approach is a bit messy as I have mixed CSS an ...

Using Angular Project: Exploring the Feasibility of Accessing SCSS Files from Node_modules in Custom Components

When setting up Angular, how can I include a Bootstrap SCSS file in a Custom Component using Style.SCSS? In Angular.json { "$schema": "./node_modules/@angular/cli/lib/config/schema.json", "version": 1, "newProjectRoot": "projects", "p ...

Encountered an HttpErrorResponse while trying to access the API endpoint

I am encountering an issue when trying to update and insert data with a single post request. Below is my API code: Here is the service code: This section includes the function calling code: Additionally, this is the model being used The API C# model c ...

Having trouble retrieving a value from a reference object in React Typescript?

Struggling with a login form issue in my React TypeScript project. Below is the code for the react login form: login-form.tsx import * as React from 'react'; import { Button, FormGroup, Input, Label } from 'reactstrap' ...

When working with Typescript and React, you may encounter an issue where an element implicitly has an 'any' type because the type 'State' has no index signature. This can lead to

In my current mini project, I am using Typescript and React. As someone new to Typescript, I am currently in the process of learning it. Within the project, I have a state defined as follows: type State = { field1: string, field2: string, field3: n ...

Controller Function Utilizing Private Variable in AngularJS

After stumbling upon an Angularjs example online, I found myself perplexed. The code snippet in question is as follows: angular.module("testApp",[]).controller("testCtrl", function($scope){ var data = "Hello"; $scope.getData = function(){ ...

What is the best way to integrate an asynchronously initialized API with a Vuex state?

As I delve into the world of Vue + Vuex, I find myself grappling with the challenge of initializing an API that relies on asynchronous methods. The common solutions I've attempted so far have hit roadblocks - can't use await outside an async fun ...

Possible solutions for AngularJS using ng- tags

I absolutely love incorporating AngularJs into my Multiple Pages Laravel Application. However, using the Laravel Blade Template Engine has made me reconsider adding Angular Tags to clutter my blade templates. For instance <div ng-controller="TodoCont ...

Is there a way to efficiently convert several strings within an object that has been retrieved from an HTTP request into another language, and subsequently save this object with the

Is there a way for me to translate some strings in an object before storing it in another http request using the Google Translate API? I am currently getting the object from one http request and saving it with a put method. How can this be achieved? servi ...

Custom Angular directive for collapsing sub menus with CSS

I found a helpful article on creating collapsible menus and submenus using only Bootstrap and custom code for Angular 2, 4, 5, 6. I've been able to implement the logic successfully, but I'm facing an issue with multiple menus where clicking on an ...

Set the minimum height of a section in jQuery to be equal to the height of

My goal is to dynamically set the minimum height of each section to match the height of the window. Here is my current implementation... HTML <section id="hero"> </section> <section id="services"> </section> <section id="wo ...

Looking to expand the width of the sub menu to reach the full width of the

Is there a way to use CSS to make a sub-menu start from the left side of the screen instead of starting it below the parent item? nav { margin: 0 auto; text-align: center; } nav ul ul { display: none; } nav ul li:hover > ul { di ...

"Cookie Magic: Unleashing the Power of Ajax and

I am currently working on an ASP.NET 3.5sp1 application with a single page layout where all interactions are handled through ajax, eliminating the need for postbacks. The website in question is . This app does not require user accounts and allows anonymou ...

Tips for clearing out text in a <p> tag with javascript when it exceeds a specific length of 100 characters

Is there a way to automatically truncate text to (...) when it exceeds 100 characters inside a paragraph with the class .class? For instance, if I have a long paragraph like this: <div class='classname'> <p>Lorem ipsum dolor sit ame ...

Submitting an Ajax form refreshes the page

After submitting the form, the page reloads and I am trying to prevent that from happening. Latest Update: After receiving some feedback, I have made changes to my code. The form submission now works correctly, but the page still reloads. Previously, this ...

What is the best way to organize React components/modules in order to effectively separate the UI?

Currently, I have developed three key components for a dashboard UI project in React. These components include a sidebar, top navigation bar, and a content container. As someone who is new to React after working with Angular, I am now seeking advice on how ...

Setting up an Express route for updating data

I am in the process of developing a MEVN stack CRUD application (Vue, Node, Express, MongoDB). I am currently working on setting up an Express route for handling updates in my app... postRoutes.post('/update/:id', async(req, res)=> { cons ...

Div sliding out of view

I'm encountering a slight issue with this template: essentially, my goal is to implement a feature where clicking on a box will expand it while simultaneously sliding the other boxes off-screen. However, instead of just sliding the div off-screen, it ...