Ways to assign a random color to every card displayed in a screenshot in Angular 6?

[![enter image description here][1]][1]

This is the HTML component code:

<div class="row">
  <div class="col-lg-3 col-md-3 col-sm-6 col-12">
    <a href="javascript:void(0)" (click)="openModal()">
      <div class="card card-box HYT " style="border: 1px dashed #3987d9;">
        <div class="card-body ">
          <div class="vimg rect-0">
            <h4 class="KLIU"> <i class="fa fa-plus" aria-hidden="true"></i> Create New</h4>
          </div>
        </div>
      </div>
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-6 col-12"  
    *ngFor="let rlist of appList | search : query | paginate: { itemsPerPage:10 , currentPage: p }; let i = index;">
    <a href="javascript:void(0)" >
      <div class="card card-box HYT ">
        <div class="card-body ">
          <div [class]='"vimg rect-"+(i+1)'>
            <h4 class="HTRE"><img [src]="rlist?.attributes?.applogo" width="100%"></h4>
          </div>
          <span class="PKU">{{rlist?.attributes?.appname}}</span><br>
          <span class="KHUY">Create-On: {{rlist?.createdAt |date: 'EEE, dd-MMM-yyyy'}}</span>
          <i class="fa fa-edit" (click)="editModal(rlist?.id)"></i>&nbsp;
          <i class="fa fa-trash" (click)="deleteApp(rlist.id)"></i>&nbsp;
        </div>
      </div>
    </a>
  </div>
  <div class="col-12" *ngIf="appList.length>0">
    <ul class="pagination" style="padding-top:25px; margin-left: 35%;">
      <pagination-controls (pageChange)="p = $event"></pagination-controls>
    </ul>
  </div>
</div>

This is the TypeScript component code:

async getApps() {

    const AppInfoData = Parse.Object.extend('w_appinfo');
    const query = new Parse.Query(AppInfoData);
    this.appList = [];

    this.appList = await query.descending("updatedAt").find().then(function (result) {
      return result;
    }, (error) => {
      this.toastr.error(error.message, 'Error!!!');
    });

  }

In the provided screenshot, I manually applied colors to the app list. I am looking for a way to assign a random color to each card whenever the 'create new' button is clicked. Any assistance on how to achieve this would be appreciated.

Answer №1

Here is an example you can follow:

View Demo

.ts

  updateColors() {
    this.itemsList.forEach(item => {
       item.color = '#' + Math.floor(Math.random()*16777215).toString(16)
    });
  }

.html

<div class="content " [style.background-color]="item.color">
   ...
</div>

Answer №2

If you want to change color randomly, you can utilize NgStyle for that purpose.

To achieve this, simply insert the following code wherever you wish to implement the color change:

[ngStyle]="{'color': getRandomColor()}"

Make sure to include the getRandomColor() method in your code as shown below:

getRandomColor() {
    var color = Math.floor(0x1000000 * Math.random()).toString(16);
    return '#' + ('000000' + color).slice(-6);
  }

For a practical demonstration, you can refer to this StackBlitz example of Random Color Generation.

We hope this information proves helpful to you!

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

Steps for converting an observable http request into a promise request

Here is a link to my service file: https://i.sstatic.net/8dsMx.png This is the TypeScript file for my components: https://i.sstatic.net/of6sx.png And these are the response models: https://i.sstatic.net/U8RUQ.png https://i.sstatic.net/7baTj.png I am curre ...

How does the call method on array.prototype.includes work with arguments x and y?

Curious about the functionality of array.prototype.includes.call(x, y);. Discovered that includes() confirms if an array has the specified value and provides a true or false result. Learned that call() invokes this alongside any optional arguments. The ...

Guide to fetching a string using Angular's http client?

I am facing an issue with calling a server that returns a csv file as text. I am using Angular's HttpClient and I need to prevent it from trying to cast the csv file to JSON. I tried setting the responseType to 'text' in the httpOptions, but ...

Building a theme with TypeScript in React

As I embark on my React project, I've been tasked with creating a CSS using TypeScript while referring to the color palette diagram provided below. Utilizing createMuiTheme to build the theme, I've realized that there are various possible conditi ...

Refreshing user information on Ionic platform

Hello there, I am seeking assistance on updating user data in Angular and Ionic. I have managed to retrieve the user ID from local storage and create a method to store the new user data. However, I'm struggling with updating the user with this new inf ...

What purpose does the class serve in typescript?

This is a unique version of app.component.ts in the Angular Tour of Hero tutorial. import { Component } from '@angular/core'; export class Superhero{ name : string; id : number; } const SUPERHEROES : Superhero[] = [ {name : 'Wonder ...

Exploring the various methods of setting up a Create React App project with TypeScript

One of my old books from a year ago mentioned... npx create-react-app XXX --typescript But looking at the current Create React App documentation, it says... npx create-react-app XXX --template typescript They both seem to yield the same result. Is ther ...

My component is displaying a warning message that advises to provide a unique "key" prop for each child in a list during rendering

I need help resolving a warning in my react app: Warning: Each child in a list should have a unique "key" prop. Check the render method of `SettingRadioButtonGroup`. See https://reactjs.org/link/warning-keys for more information. at div ...

Implementing dynamic progress bar updates in an Angular application using Bootstrap

Seeking to create a progress bar in a Word object for a language vocabulary training app, displaying the number of correct and wrong answers. <div class="progress"> <div class="progress-bar progress-bar-striped progress-bar-a ...

Angular reactive form pattern validator restricts input to text, digits, and certain special characters

I am currently working with Angular 10 and reactive forms. I have a requirement where an input field should only accept letters, numbers, and the special characters "_" and "-". I have attempted to allow letters and numbers using the following code: Valid ...

Leveraging OAuth 2 with Google

I'm currently working on implementing Google API for user authentication. I have successfully managed to authenticate users, but I am struggling with redirecting users after Sign In and implementing Sign Out functionality. I have been referring to th ...

An issue occurred: Promise was not caught and resulted in an error stating that no routes can be matched for the URL segment 'executions/190'

My current project involves developing the front end by mocking the back-end using the expressjs library. Within my project, I have a file called data.json which stores objects like the following: "singleExecutions":[ {"executionId":190, "label":"exe ...

When clicking the button, the service function is not properly updating the view

Upon calling this.getLeaderboard(); in the ngOnInit() function within leaderboard.component.ts, the leaderboard is only displayed on page load or refresh, which is expected. However, I also want to retrieve and display the leaderboard upon clicking a butto ...

Disable inline imports when implementing an interface in vscode by selecting the "Implement interface" option

When using TypeScript, if I perform an auto-fix on a class name by selecting "Implement interface", it will generate the methods with inline imports like this: getInbox(): Observable<import('../../model/Message').Interactions[]> { t ...

Execute the function right away and then at regular intervals of X seconds

Need help with Angular 7 function call timing checkData(): Observable<string> { return this.http.get('') .pipe( map(res => { let result; result = { packageNumbe ...

Is your async function lacking a return statement?

After completing the development of a new method for a bug I encountered, I noticed something interesting. Despite the fact that there is a potential scenario where the function may not return anything, the compiler did not flag any errors. It got me think ...

Is it possible to expand or merge Nestjs decorators?

My custom decorator named "User" is quite simple: export const User: () => ParameterDecorator = createParamDecorator( (data: any, req): UserIdentity => { const user = getUser(req); return user; }, ); Now, I'm in need of validating ...

What is the best way to enhance the object type within a function parameter using TypeScript?

If I have a specified type like this: type Template = { a: string; b: string; c: string } I want to utilize it within a function, but with an additional parameter. How can I achieve this efficiently? When attempting to extend the type, TypeSc ...

Navigating resolvedUrl with getServerSideProps in the newest version of NextJS - a comprehensive guide

Is there a way to obtain the pathname without using client-side rendering? I have been searching for information on how to utilize the getServerSideProps function, but so far with no luck. Initially, I attempted to employ usePathname; however, this result ...

An easy guide on utilizing ngSwitch for datatype selection in Angular

While working in angular2, I came across a question regarding the usage of ngSwitch to load <div> tag based on the datatype of a variable. Is it possible to achieve something like this: <div [ng-switch]="value"> <p *ng-switch-when="isObj ...