Using string interpolation and fetching a random value from an enum: a comprehensive guide

My task is to create random offers with different attributes, one of which is the status of the offer as an enum. The status can be “NEW”, “FOR_SALE”, “SOLD”, “PAID”, “DELIVERED”, “CLOSED”, “EXPIRED”, or “WITHDRAWN”. I need to generate a random offer with randomized attributes and a random status from the enum.

I've tried various approaches but I'm struggling to use the enum in this scenario. String interpolation doesn't seem to work with the enum, and I'm unsure how to apply randomization to it.

export class Overview1Component implements OnInit {
  private offers: Offer[];

export class Offer {
  public title: string;
  public sellDate: Date;
  public description: string;
  public auctionStatus: AuctionStatus;
  public numberOfBids: number;
  public valueHighestBid: number;
}

export enum AuctionStatus {
  NEW = 1,
  FOR_SALE = 2,
  SOLD = 3,
  PAID = 4,
  DELIVERED = 5,
  CLOSED = 6,
  EXPIRED = 7,
  WITHDRAWN = 8
}

Am I approaching the enumerator incorrectly? How can I select a random value from the enum and display it using string interpolation in my HTML?


Additional information:

To create random offers, I use the following method:

 public addRandomOffer(): void {
    const newOffer = new Offer();
    newOffer.title = 'This great article offer-' + (this.offers.length);
    const fromDate = new Date(2005, 0, 1);
    const toDate = new Date(2020, 0, 1);
    newOffer.sellDate = this.getRandomDate(fromDate, toDate, 0, 23);
    newOffer.numberOfBids = Math.floor(Math.random() * 30 + 1);
    if (newOffer.numberOfBids === 0) {
      newOffer.valueHighestBid = 0;
    } else {
      newOffer.valueHighestBid = Math.floor(Math.random() * 200 + 1);
    }
    this.offers.push(newOffer);
  }

The current method does not include randomizing the status, as I'm unsure how to implement it.

This process allows for random offers to be displayed on an overview component.

View Image

In the HTML for printing the offers, the code looks like this:

  <tr *ngFor="let offer of offers">
    <td>{{offer.title}}</td>
    <td>{{offer.sellDate}}</td>
    <td>{{offer.auctionStatus}}</td>
    <td>{{offer.numberOfBids}}</td>
    <td>€{{offer.valueHighestBid}}</td>
  </tr>

Answer №1

Here's a concise version:

class Offer {
  constructor() {
    this.auctionStatus = Math.trunc(Math.random() * 8 + 1);
  }

}

const offer = new Offer();
console.log(offer.auctionStatus);

Simple and straightforward.

However, if you're wondering, I recommend using objects instead of enums in JavaScript. Enums are not native to JS, so go with objects for better compatibility.

(Of course, that's just my personal preference).

Answer №2

If you need to retrieve a random enum value using an index accessor, you can accomplish this with the following code snippet:

AuctionStatus[Math.trunc(Math.random() * 8 + 1)]

For accessing the total number of values in the enum, you can utilize the following clever trick:

Object.keys(AuctionStatus).length / 2

To see an example in action, visit Stackblitz at: https://stackblitz.com/edit/angular-get-random-enum-value

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

The Angular CLI is consolidating all component styles within the head section of the document

Currently, all CSS for a page's components is being injected into the head of the document. Is it possible to consolidate these styles into a separate file that can be linked in the head of the document, similar to how external CSS libraries like boot ...

What could be causing my data to undergo alterations when transitioning from a frontend form submission to a backend API?

In my experience with Next.js 13 and Prisma, I encountered a peculiar issue. I had set up a basic form to collect user information for an api request. Oddly enough, when I printed the data right before sending it, everything seemed fine. However, upon arri ...

add headers using a straightforward syntax

I'm attempting to append multiple header values. This is what I'm currently doing: options.headers.append('Content-Type', 'application/json'); options.headers.append('X-Requested-By', 'api-client'); ... ...

Tips on using services for storing and fetching list data in Angular

I currently have two components, the "add-expense" component and the "view-list" component. The "add-expense" component collects expense details from a form and stores them as an object. My goal is to add this object to an empty list within the "expense-li ...

Using conditional CSS values in Angular 8

I am currently working on a parent component and child component setup, where I am utilizing the child component's selector to display it within the parent component. Here is my child component's HTML: <div class="main-container" [n ...

What could be causing the global npm package to not be utilized for module dependencies?

My typescript and ts-node are already installed globally. In my package.json file, I have the necessary configurations to run tests with npm test. Everything works fine since ts-node and typescript are installed as local modules. { "name": "two_sum", ...

Is there a method to refresh the Monaco editor or clear existing models within it?

Currently, I am utilizing ngx-monaco-editor to create a code editor within a modal window. In order to support multiple tabs, I am looking to create a map for the models to keep track of them along with their URIs. Furthermore, it is important that the mod ...

Enhance Your GoJS Pipeline Visualization with TextBlocks

I am facing challenges in customizing the GoJS Pipes example to include text within the "pipes" without disrupting the layout. Although I referred to an older response on the same query here, it seems outdated or not detailed enough for me to implement wit ...

Create a TypeScript function that can be called and has an extended prototype definition

I am seeking to create a callable function foo() (without using the new operator) that will also include a property foo.bar(). The JavaScript implementation would be as follows: function foo() { // ... } foo.prototype.bar = function bar() { // .. ...

Initialization issue detected in Angular's module APP_INITIALIZER

In my auth module, I have implemented a mechanism to import and set up MSAL configuration before initializing the app. I am using APP_INITIALIZER to delay the initialization of the app until the configuration for MSAL-ANGULAR is retrieved. The issue I am f ...

Typescript error: The property "Authorization" is not found in the type HeadersInit

As I utilize the npm module node-fetch, I have a helper function specifically designed to facilitate authorized requests to a third-party service. This function essentially acts as middleware by incorporating the Authorization header. async function makeAu ...

Guide on Integrating RDLC Reports with Angular 7

I currently have a window application that contains multiple RDLC reports. As I am transitioning this window application to Angular 7, I am wondering if there is a way to utilize my existing RDLS reports in Angular 7? While I have come across suggestion ...

How should a string be properly converted to JSON format?

I am encountering an issue with converting the following string to JSON format const banner = " { "banners": [ { "startDate": "02/26/2021", "endDate": "12/25/2021","content": "Important ...

What causes the discrepancies in versions of dependencies listed in the package-lock.json file?

Currently, I am developing an application using angular 10. I have noticed that the version of a dependency in my package-lock.json file is different from what I specified in my package.json after running the command: npm install. For example: In my pack ...

The Angular 7 template falls short of occupying the entire page

I am currently working on converting an HTML page into my Angular project. While it functions correctly in the HTML version, it does not fill up the entire page when transferred to Angular. You can view an example of this issue on StackBlitz at the followi ...

Error in pagination when using MAX() function in PostgreSQL query

Here is the query I am using to retrieve the latest message from each room: SELECT MAX ( "Messages"."id" ) AS messageId, "Rooms"."id" FROM "RoomUsers" INNER JOIN "Rooms" ON " ...

ng2-idle server side rendering problem - Uncaught ReferenceError: document is undefined

Can ng2-idle be used for idle timeout/keepalive with pre-rendering in Angular 4? I followed this link for implementation: It works fine without server pre-rendering, but when I add rendering back to my index.html, I keep getting the following error: Exce ...

Altering a public variable of a component from a sibling component

Within my application, I have two sibling components that are being set from the app.component: <my-a></my-a> <my-b></my-b> The visibility of <my-a> is determined by a public variable in its component: @Component({ module ...

Explore an example of using custom controls in a FormArray within an Angular 5 reactive form on StackBlitz

Check out my sample project on stackblitz that tests nesting components and retrieving the complete form value. https://stackblitz.com/edit/mensand-hobbies-football-tennis This is a demonstration where I aim to utilize different components stored in an a ...

I am puzzled by this error in Typescript: "Why does the element have an 'any' type when the Object type lacks an index signature?"

Looking to extract an array of keys from an object with nested properties, my current code: public static getKeys(obj: Object) { let keys: string[] = []; for (let k in obj) { if (typeof obj[k] == "Object" && obj[k] !== null) { ...