Changing the background color within an *ngFor loop using Angular 2's ng-style

Looking to add unique background colors using ng-style. Each row in the list is created with ngFor, giving each item its own distinct background color.

<ion-item class="category-list" *ngFor="let item of character['items']">
   <ion-avatar item-left>
  <i class="icon" [ngStyle]="{'background-color': item.bgcolor}"><img src="../img/icons/category/{{item.img}}.png"></i>
  </ion-avatar>
    <h2>{{item.category}}</h2>
  </ion-item>

Here's a snippet from the Typescript.ts:

 var characters = [
  {
    name: 'Gollum',
    quote: 'Sneaky little hobbitses!',
   items: [
      { bgcolor: 'fb9667', img: 'airTicket', category: 'Air tickets' },
      { bgcolor: '000000', img: 'airTicket', category: 'Beauty/Fitness'},
      { bgcolor: '0b9660', img: 'airTicket', category: 'Bike'}
    ]
  },
]

Having trouble applying color codes to the list—any advice?

Answer №1

To alter the background color, you can utilize the [style.backgroundColor] property:

<i class="icon" [style.backgroundColor]="item.bgcolor"></i>

Assuming that the value in item.bgcolor corresponds to a valid CSS color string:

#FFFFFF white rgb(255,255,255) rgba(255,255,255,1)

In your particular situation, it does not match. You need to include the leading # and adjust your item list as follows:

items: [
      { bgcolor: '#fb9667', img: 'airTicket', category: 'Air tickets' },
      { bgcolor: '#000000', img: 'airTicket', category: 'Beauty/Fitness'},
      { bgcolor: '#0b9660', img: 'airTicket', category: 'Bike'}
]

Answer №2

Simply add this CSS code to your stylesheet and watch as every other row changes color:

list { background: green; }

list:nth-child(odd) { background: red; }

Answer №3

Here is a helpful tip for fellow developers in the future. Below is the code snippet that loops through colors and assigns them to each row generated by ngFor.

<ion-col [ngStyle]="{'background-color': getColors(i) }" *ngFor="let data of Data; let i = index">
Colors: Array<any> = ["#FFF","#0b9660","#FF0000","#000","#FFF","#ffd11a","#fb9667"];

getColors(index) {

    let num = this.getNumber(index);
    return this.Colors[num];
}

getNumber(data){

    let i = data;
    if(i >= this.Colors.length){
        i -= this.Colors.length;
        if(i < this.Colors.length){
            return i;
        }
        else {
            return this.getNumber(i);
        }
    }
    else {
        return i;
    }

}

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

My Discord bot is having trouble functioning with slash commands in discord.js

I previously raised an issue regarding my discord.js bot not responding to user messages even when no errors are detected. Although the solution I implemented works for messages, it does not seem to work with commands. Additionally, I have enabled the app ...

Resolving the problem with iterating through $list using SCSS/SASS @mixin

Consider the following list: $box-shadow-properties: -webkit-box-shadow, -moz-box-shadow, box-shadow; I am attempting to create a mixin that iterates through this list: @mixin box-shadow-with-inset($box-shadow-params, $inset-params) { @each $property ...

What is the best way to add an image using php, javascript, and browser storage?

Previously, I successfully uploaded an image using PHP and HTML. Now, I need to achieve the same with JavaScript (js) and AJAX. Additionally, I have been advised to utilize local storage for server-side storage before inserting it into the database. Below, ...

How can Cognito be integrated on a pure HTML & JS website, with or without using Amplify?

After diligently reading through the documentation provided by AWS which mainly focuses on React JS, I am feeling a bit lost. My goal is to set up the sign-in, sign-up, and login components but the process seems complex. I stumbled upon an alternative met ...

Prevent further clicking on a button in a custom Drupal module after it has been clicked three times

I'm new to using Drupal and have created a custom module similar to webform. In my module page, I have two submit buttons and 2 textboxes as shown below: function contact_request($form, &$form_state) { $form ['info'] =array( &ap ...

Is there a way to showcase the JSON data within a nested array using VueJS?

Here is my Vue.js code: <script> new Vue({ el: '#feed' , data: { data: [], }, mounted() { this.$nextTick(function() { var self = this; var id = window.location.href.split('=').pop(); ...

Is there a way to use JavaScript to change the text displayed in this ASPX control?

On an ASPX page, I have the following input control: <input tabindex="0" class="_f_ql _f_rl textbox allowTextSelection placeholderText" role="textbox" aria-labelledby="MailCompose.SubjectWellLabel" autoid="_f_B2"></input> I am limited to inje ...

Having trouble with CSS styling not applying after website is uploaded to server?

I have taken a basic page template that was originally designed for the rest of my website and customized it to appear more simplistic. The page now consists of an unordered list with a brief paragraph at the top and a logo aligned to the right. While ever ...

Using jQuery to measure the height of a div consistently shows a value of 1

I'm attempting to retrieve the height of a specific div using the following code: var divHeight = $("#myDiv").height(); referencing information from the JQuery documentation <div style="width: 300px; height: 300px;"></div ...

What is the best way to arrange text inputs in alignment?

I encountered an issue while creating a form that includes fields for username, password, and email. The alignment of the email input box seems to be off when compared to the username and password input boxes. Is there a method to ensure that all the input ...

Styling elements using flexbox and various other divs

Looking to style a webpage with CSS to achieve this particular layout: https://i.sstatic.net/K3x0A.png The objective is to make the page responsive where the red and blue columns (left and right) have fixed widths. The center column should be collapsible ...

What is the reason behind Webpack's behavior of loading all files from a folder during lazy loading

I am attempting to dynamically import i18n files using webpack: function getI18n(lang) { return import(/* webpackChunkName "i18n/[request]" */ `./locales/${lang}.json`) .then(/*whatever*/) } However, I have noticed that all the files from the specifi ...

Use Angular2 to showcase the selected image as the main one when the user clicks on the

I'm working on creating a product thumbnail gallery, and I'd like the main image to be displayed when the user clicks on a thumbnail. I am using Angular for this project, although I am still learning my way around the framework. product.html &l ...

Can anyone offer any suggestions for this issue with Angular? I've tried following a Mosh tutorial but it's

Just finished watching a video at around 1 hour and 35 minutes mark where they added the courses part. However, I encountered an error during compilation. ../src/app/app.component.html:2:1 - error NG8001: 'courses' is not recognized as an elemen ...

Generating fresh Mongodb Records versus Appending to a Document's Collection

A device that records temperature data every second feeds into a real-time chart using Meteor.js to display the average temperature over the past 5 seconds. Should each temperature reading be saved as a separate MongoDB document, or should new readings be ...

What is the xui equivalent of jquery's slideUp/slideDown function?

Hello, I am experimenting with creating a similar effect to jQuery's slideUp and slideDown function using [xui](http://xuijs.com). So far, I have successfully implemented the fade effect: xui.extend({ fadeOut:function(dur, callback) { ...

Switching from HttpModule to HttpClientModule

Angular's transition from HttpModule to HttpClientModule is causing some confusion, as discussed in detail here. The official Angular tutorial at https://angular.io/tutorial/toh-pt6 still uses HttpModule, while the Fundamentals documentation at https ...

scope of variables and closures within a module pattern in a JavaScript object

Currently, I am developing a jQuery plugin using unconventional methods in order to prioritize portability and expandability. I am encountering difficulties accessing variables that were initially declared within the function when trying to access them fr ...

ng-class not functioning properly when invoked

In my controller, I have the following function: $scope.menus = {}; $http.get('web/core/components/home/nav.json').success(function (data) { $scope.menus = data; $scope.validaMenu(); }).error(function () { console.log('ERRO') }); ...

Enclose the quotes within an array in JSON format

I've been attempting to construct a JSON array, but I'm encountering some issues: var sample = '{"sections":[{"id":"example1", "title":"Data Analysis", "command":"openSection("analysis")"}]}'; I've identified the problem with the ...