Ways to allocate a random color within an array?

Hi there, I'm trying to create chips with random colors from an array in my code. I attempted to use a color string array and assign them to the chips one after the other, but it didn't work as expected. Any suggestions on how I can achieve this?

HTML

<ion-chip [color]="color" class="chip" #chip *ngFor="let tag of tagName">

TS

 public color: string [] = ["ok", "nice","awesome","danger","white"]

tagName

export class Tag {
  tag: string;
  constructor(value: Object = {}) {
    Object.assign(this, value);
  }

...

  tagName: Tag[] = [];

...

  add(): void {
      let id = this.tagName.length + 1;
      this.tagName.push(new Tag({ tag: "tag" + id }, ));
    }

    remove(tag: Tag) {
      let id = this.tagName.indexOf(tag);
      this.tagName.splice(id, 1);
    }

Answer №1

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

Capture:

https://i.sstatic.net/yHbG9.png

Answer №2

To start, the first step is to create a random index within the range of 0 to the size of your array:

generateRandomIndex(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

Next, assign a color using this method:

[selectedColor]="colors[generateRandomIndex(colors.length)]"

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

:host background color may be missing, but the font size has been boosted?

Check out this demo where the CSS is applied to the :host element or <hello>. The font size increases but the background color remains unchanged. What do you think? styles: [` :host { font-size: 2rem; background-color: yellow; }`] }) ...

Error: Unable to retrieve data - Angular2 application encountered a XHR error with status code 404 (

Hey there, I recently started working with angularjs and created a demo app using angular2. However, when I try to run the application, I encounter an error. Interestingly, even though the error mentions a 404 status code, if I visit the URL http://loc ...

Error: The argument provided cannot be assigned to a parameter that requires a string type, as it is currently a number

Currently, I am in the process of migrating some older websites to TypeScript. However, I keep encountering a type error during the build process. The specific error message is Type error: Argument of type 'number' is not assignable to parameter ...

Is there a way to execute my asynchronous function within a loop?

After numerous attempts to run an async function that sends a post request to the server and logs the response in the console, I'm still facing issues. Despite looking at similar questions on stackoverflow, nothing seems to be resolving my problem. N ...

Guide on adding a button to a mat-table in Angular

I am looking to add a delete button or an Angular trash icon to a mat-table in an Angular application. Can anyone guide me on how to achieve this? Here is my current table code: <mat-table #table [dataSource]="ELEMENT_DATA"> <ng-container cdk ...

Learning to display an error message by clicking the send button in an Angular 2 application

Despite my best efforts, I have struggled to find a solution. I have searched various websites, but everywhere they only show validations on touch or hide the button until the form is valid. How can I implement validations by simply clicking a button? Here ...

Angular messaging service error TS2769: There is no overload that fits this call

Currently, I am attempting to utilize a messenger service to send products to the cart component. Within the 'Product' class, there are various product attributes stored. Although I managed to successfully log the product to the console in the ca ...

Update the js file by incorporating the import statement

Currently, I am in the process of transitioning to using imports instead of requires for modules. Here is an example of my previous code: const { NETWORK } = require(`${basePath}/constants/network.js`); The content of network.js file is as follows: export ...

Error occurs when Protractor end-to-end tests encounter a problem with browser.executeAsyncScript

I encountered an error while attempting to implement e2e testing for our application. My initial test case failed with the following error message: Failed: Error while running testForAngular: javascript error: Unexpected identifier JavaScript stack: ...

Incorrectly selecting an overload in a Typescript partial interface can lead to errors

My attempt to define an overload for my function using a Partial interface overloading is causing typescript to select the incorrect overload interface Args { _id: string; name: string; } interface Result { _id: string; name: string; } function my ...

What is the best way to set up a FormGroup when the FormControlName is dynamic and subject to change?

Hello, I am new to Angular and encountering a particular scenario. On my HTML page, there is a form (formgroup) with a div inside it that uses the ngFor directive to iterate through an object as needed. Let's say there is an input field with formCon ...

ngModel Error: Unable to retrieve the 'name' property of an undefined value

I have a JSON file that displays different levels of data, some in regular format and some as arrays as shown below. [![enter image description here][1]][1] However, I keep encountering an error message like the one below: [![enter image description her ...

The request to DELETE the employee on the server at http://localhost:3000/employees/$%7Bid%7D could not be processed because it was not found

removeEmployee(id: number): Observable<any> { return this._http.delete('http://localhost:3000/staff/${id}'); } } error:HttpErrorResponse {headers: HttpHeaders, status: 404, statusText: 'Not Found', url: 'http://localhost:30 ...

Every time I select a value for the first time, the ng-repeat array updates table data, but it doesn't update the table data just once

I am facing an issue with updating the table view based on select option in my project. The problem is that the table view updates only once when I select the option for the first time, but it doesn't update when I choose the option again. I'm ha ...

The 'innerText' property is not found in the 'Element' type

Currently, I am working with Typescript and Puppeteer. My goal is to extract the innerText from an element. const data = await page.$eval(selector, node => node.innerText); However, I encountered an error: The property 'innerText' is not ...

Is there another way to implement this method without having to convert snapshotChanges() into a promise?

When trying to retrieve cartIdFire, it is returning as undefined since the snapshot method is returning an observable. Is there a way to get cartIdFire without converting the snapshot method into a promise? Any workaround for this situation? private asyn ...

Despite enabling CORS for a specific origin, I am still encountering the error message "No 'Access-Control-Allow-Origin'"

In my front-end application, I am using Angular to request API responses from a web API core project. Despite setting up cross-origin resource sharing for both running on different origins, I am still encountering an error stating 'No Access-Control-A ...

`How can TypeScript be used to designate the type of a variable within the useState hook?`

I defined a variable called 'text' and a hook named 'setText'. I'm using them to update the value of a form input field. How can I ensure that 'text' is always of type string? This is what I attempted: interface TextInt ...

Transform a string into a class in Typescript/Angular

In my application, I've created a reusable modal popup component that takes a string as input and dynamically loads other components based on that input. This approach allows me to use the same modal popup component for multiple modals in the app inst ...

Improve the way you manage the active selection of a button

ts isDayClicked: { [key: number]: boolean } = {}; constructor() { } setSelectedDay(day: string, index: number): void { switch (index) { case 0: this.isDayClicked[0] = true; this.isDayClicked[1] = false; this.isDay ...