Troubleshooting scope variable issues with the ngStyle binding in Angular

Below is the code snippet for a component I have:

@Component({
  template: `
  <div class="container">
    <div *ngFor="let connection of connections">
      <div class="row">
        <div class='col-2'>{{connection.arrivalTime}}</div>
        <div class='col-1'>{{connection.delay}}</div>
          <div class='col-2'>{{connection.actualArrivalTime}}</div>
          <div class='col-1'>{{connection.icon}}</div>
          <div class='col-1'><span [ngStyle]="{'background-color': connection.colors.bg}">{{connection.line}}</span></div>
          <div class='col-3'>{{connection.direction}}</div>
          <div class='col-2'>{{connection.cancelled}}</div>
        </div>
      </div>
    </div>
styleUrls: ['../app.component.css', '../../simple-grid.css'],
})
export class ZVVComponent {


 connections: PublicConnection[] = [];
  displayDate: Date;

  constructor(private zvvService: ZVVService) {

    this.displayDate = new Date();

   zvvService.getConnections(this.displayDate).subscribe(data => {
      data.forEach( (connection) => {
        this.connections.push(new PublicConnection(
          connection.product.line,
          connection.product.longName,
          connection.product.direction,
          connection.cancelled,
          connection.product.icon,
          connection.product.color,
          connection.mainLocation.time,
          connection.mainLocation.countdown,
          connection.mainLocation.realTime.time,
          connection.mainLocation.realTime.countdown,
          connection.mainLocation.realTime.delay,
          connection.mainLocation.realTime.isDelayed,
          connection.mainLocation.realTime.hasRealTime
        ));
      });
    });
  }
}

Within one of the divs, I used ngStyle to bind it to the variable `connection.colors.bg`, which contains a hex string representing the color:

export class Color {
  get fg(): string {
    return this.fg;
  }

  get bg(): string {
    return this.bg;
  }
}

However, despite my efforts, the text still shows up in black with a white background. When I manually change it to 'red', the text appears as red. What am I missing here?

Here is the code for the `PublicConnection` class:

import { Color } from './color';

export class PublicConnection {

constructor(
  public line: string,
  private name: string,
  public direction: string,
  public cancelled: boolean,
  public icon: string,
  public colors: Color,
  public arrivalTime: string,
  private countdown: string,
  public actualArrivalTime: string,
  private actualCountdown: string,
  public delay: string,
  private isDelayed: boolean,
  private hasRealtimeData: boolean
) {
  this.direction = this.direction.replace('&#252;', 'ü');
  this.direction = this.direction.replace('&#246;', 'ö');
  this.direction = this.direction.replace('&#252;', 'ü');
}
}

Answer №1

The problem does not lie with the ngStyle directive - you are actually utilizing it correctly. The issue most likely stems from the data not being loaded when the component attempts to render initially.

Given that your data is retrieved asynchronously, my assumption is that during the component's rendering process and background color setting, it has yet to obtain a color value from the service.

To address this, consider implementing a safe navigation operator by modifying connection.color.bg to connection.color?.bg in your template.

For further information, refer to: https://angular.io/guide/template-syntax#the-safe-navigation-operator----and-null-property-paths

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

Tips for Sending Specific Row Information to Server in Ionic 3

Successfully pulled contacts from the device into my list page, but struggling to send specific contact details (name and number) to the server. Can anyone provide guidance on accomplishing this in Ionic? ...

Issues with Angular 6 Feature Modules: Interceptor failing to execute

I am delving into feature modules for the first time and struggling to get an interceptor to trigger. Adapting to the feature model pattern is a learning curve, and I am seeking guidance in identifying any misinterpretations. The named interceptor is "Auth ...

The JSON object cannot be assigned to the IntrinsicAttributes and customType data types

Currently, I'm facing a challenge with reading JSON data into an array of type pinImage. My goal is to loop/map through my pinImage objects and pass each one to a child component called PinCard, which is specifically designed to accept an object of ty ...

Showing fetched data from Firebase in an Ionic 3 HTML file

Looking for assistance on how to display data retrieved from my firebase database in my HTML file. I need help with organizing the data, starting with displaying customer user's data. Eventually, I want to make it clickable and put the user's dat ...

Struggling to align rotated text within the Bootstrap 4 Grid system

I have been working on a grid layout using Bootstrap 4's Grid system, and I am aiming for a design similar to the following: https://i.sstatic.net/sU7kV.png While I have made significant progress and got almost 100% of it complete, I am facing an is ...

"Encountering connectivity issues between NestJs and TypeORM when trying to establish a

My current challenge involves connecting to MySQL. I have set the database connection variables in a .env file located in the root directory, and I am initializing the connection in the app.module.ts file. The problem arises when I attempt to create or run ...

Tips on steering clear of the issue of "Automatic grid alignment" when working with Bootstrap?

I'm attempting to achieve something along the lines of, |--------------Empty space---------------|-----first column(aligned to the right)-----| |---logo---||------Empty space-------|----second column(aligned to the right)---- However, it is automat ...

The SonarQube code coverage differs from that of Jest coverage

I'm struggling to grasp why SonarQube and Jest coverage results differ so significantly. SonarQube coverage resultshttps://i.sstatic.net/dodGi.png Jest coverage https://i.sstatic.net/uYKmt.png https://i.sstatic.net/rakzw.png https://i.sstatic.net/ ...

The dynamic fusion of Typescript and Angular 2 creates a powerful

private nodes = []; constructor(private nodeService: NodeService) {} this.nodeService.fetchNodes('APIEndpoint') .subscribe((data) => { this.nodes.push(data); }); console.log(this.nodes) This ...

What are some ways to optimize the performance of a Select Box?

I am attempting to show a lengthy list of countries in an ion-select. Currently, there are 249 countries that I need to load. Unfortunately, the rendering performance is quite slow on my phone. <ion-list margin-top margin-bottom> <ion-item> ...

Compiling fails when creating an object literal with a generic key

I am attempting to accomplish the following task. function createRecord<T extends string>(key: T) : Record<T, T> { return {[key]: key}; // Type '{ [x: string]: T; }' is not assignable to type 'Record<T, T>' } Howe ...

The getAuth() helper found in the api directory's Clerk retrieves the following data: { userId: null }

I'm completely stuck here.. Currently working with the clerk and I am looking to access the userId of the current user using the getAuth() helper. For more information, refer to the docs: pages/api/example.ts import { getAuth } from "@clerk/n ...

Are the Bootstrap columns arranged in a vertical stack instead of side by side?

I currently have two large columns that are stacked vertically on top of one another. I want them to be side by side, like | 1 | 2 |, so that the user can view both columns simultaneously. I am seeking tips or suggestions on how to resolve this issue. Whil ...

Tips for preventing unnecessary dependencies from being installed in an Angular 10 application

I've been working on a project using Angular 10. Surprisingly, my package.json doesn't mention anything about @babel. However, every time I run npm install, an error occurs: npm ERR! 404 Not Found - GET http://private_repo/repository/npm-all/@bab ...

What is causing my div to transition repeatedly from the bottom to the top instead of the center position?

Currently, I am using React and Tailwind CSS and facing an issue with the transition property. My goal is to have a div grow in width and height from the center until it covers the entire viewport when a specific state variable becomes true. The content in ...

Unable to set a value for an Angular formcontrol

Hey there! I'm facing an issue where I am trying to assign a value to a form control in TypeScript, but it just displays as blank in HTML... :( Here is the TypeScript code snippet: constructor(private readonly messageToastService: NxMessageToastServi ...

How to vertically align radio buttons with varying label lengths using Angular and Bootstrap 4?

Is there a way to properly align radio buttons with variable length labels? When each label has a different length, the radio buttons appear misaligned. How can this be fixed? <div class="row"> <div class="form-check form-check-inline" *ngFor="l ...

What specific features does CSS3 offer in terms of background-size properties?

Let's delve into my knowledge: $, like in font-size: 14$; em, as in margin: 2em; What other units are out there? ...

Angular - Javascript - Oops! The variable 'google' seems to have gone missing after reloading the page

For my website, I utilized Angular 2+ and integrated the Google Maps Api by adding the following code to my index.html file: <script async defer src="//maps.googleapis.com/maps/api/js?[myKey]&libraries=places"> </script> ...

Can an Angular Application be created in Azure without using an App Service Plan?

Our client has chosen Azure for their custom app development, utilizing API App for the backend and Angular for the front end. Interestingly, they have opted to not use an App Service Plan for the front end. Can anyone provide insight on how an Angular f ...