Understanding the expiration date of a product

I'm seeking assistance with identifying expiration dates from a list of data. For instance, if I have a list containing various dates and there is an expireDate: 2019/11/20, how can I highlight that date when it is 7 days away? Here's an example:

<tbody>
   <tr *ngFor="let organization of organizations" (click)="openModal('companyDetail', organization.id)">
      <td>{{ organization.code }}</td>
      <td>{{ organization.title }}</td>
      <td>{{ organization.contract.condition }}</td>
      <td>{{ organization.contract.createdDate }}</td>
      <td>{{ organization.contract.period }}</td>
      <td>{{ organization.contract.expireDate }}</td>
      <td>{{ organization.contract.conditionType }}</td>
      <td>{{ organization.address }}</td>
      <td>{{ organization.address }}</td>
      <td>
          <div class="button_group">
            <button class="text-primary" (click)="updateOrganization($event, organization.id);">
               <i class="fa fa-edit"></i>
            </button>
            <button class="text-danger">
               <i class="fa fa-times-circle-o"></i>
            </button>
          </div>
      </td>
   </tr>
</tbody>

What I'm looking for is a way to display a visual notification for the expireDate when it is 7 days away using attributes like ngClass. Can anyone provide some advice or guidance?

Answer №1

Follow this approach


import { Component } from '@angular/core';
import moment from 'moment'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  datesArray = ['2019-11-25', '2019-11-23', '2022-12-12','2018-12-12','2032-12-12', '2042-12-12'];

  getColor(date){
    console.log(new Date(date));
    console.log(moment().day(7).toDate());

    if( new Date(date) < moment().day(7).toDate()){
      return 'red';
    }
  }
}

In the html file, add the following code:

<div [ngStyle]="{'color':getColor(date)}">{{ date }}</div>

View a StackBlitz example here

Answer №2

When working with dates

 getDateDifference() {
        let currentDate = new Date();
        //let expiryDate = new Date();
        //expiryDate.setDate(expiryDate.getDate() + 7);
        let expiryDate = new Date('2019/11/25');
        expiryDate.setDate(expiryDate.getDate());
        let timeDifference = expiryDate.getTime() - currentDate.getTime(); 
        // Calculate the difference in days between two dates
        let dayDifference = timeDifference / (1000 * 3600 * 24); 
        return dayDifference;
    }

when incorporating it into your template file

<td [ngClass]="{'error': getDateDifference() <  7}"> {{ organization.contract.expiryDate }}</td>

in your css file make sure to include

.error {
    color: red
}

Feel free to adjust this code snippet to fit your requirements

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

Selecting the checkbox will activate the POST endpoint

I am working on a nodejs/express app and looking for a way to update my database using a POST route when a checkbox is clicked. The challenge I am facing is that I want to avoid using a submit button or jQuery. I am currently using a Bootstrap4 checkbox ...

unable to retrieve getters within the store module

This is the explanation of my store module. // rest defined earlier const _GETTERS = { getName: state => { return state.current.name; }, getLastName: state => { return state.current.lastName; }, getFullName: (state, getters) => ...

Upon clicking the "show more information" button on the page, JavaScript executes the function to display additional details

<a href="#" class="button">Read More</a><br> I'm currently struggling with programming a button on my website. Specifically, I need the Read More button to display all information related to the CDs I have for sale when clicked. A ...

Retrieve the content of a file and convert it into JSON or GeoJSON format

Can someone help me with my issue? I am struggling to extract content from geojson files and assign it to a valid variable. Here is what I've tested: //this works var obj_valid = {"type": "FeatureCollection","crs": { "type": "name", "properties": { ...

Tips for integrating AngularJS into Zend Framework 2

Hi there! I am a newcomer to Zend Framework 2 and I am exploring the integration of AngularJS into my project. Currently, I am calling a function in the controller like this: return new ViewModel(array( 'result' => $result, 'use ...

Refreshing Dropotron Data with jQuery

I'm struggling to find a solution for refreshing the <ul> and <li> elements after the page has already loaded. My <li> element is updated with Ajax data, but despite using jQuery to manipulate the DOM, the changes are not reflected ...

unable to use split method in node js during put operation

I am currently working on an update action within my Node.js project. When new data is inputted, I am experiencing a peculiar issue. When I input fresh data, the split method functions properly. However, if I input the same data again, the split method fa ...

Tips on using the $.grep() method in jQuery to filter dynamic inputs

When using the "grep" function in jQuery to filter data, the code sample below works well for static conditions. However, if the "name" and "school" parameters have multiple values, how can we filter them? Let's say I receive the name and school from ...

What is the best way to set up my page to detect the "enter" key input when the form is not created with the <form> tag?

Within the HTML code, data is received and stored in variables within my TypeScript file. At the end of the HTML, there is a button that was created separately from any user input containers. This button triggers a function that processes the information i ...

Transforming JSON data into a dynamic Tableview

I've been experimenting with this issue for quite some time now, but I can't seem to find a solution. My API returns tasks in JSON format. When I print the data using Ti.API.info(this.responseText), it looks like this: [INFO] [{"created_at":"20 ...

Is there a way to continue a failed fetch request?

I am curious about the possibility of resuming an incomplete fetch request if it fails due to a non-code-related issue, like a lost network connection. In one of my current projects, we send a large download via AJAX to the client after they log in. This ...

Interactive web page with dynamic JQuery functionality and navigable page links

I am working on the project/index.html page <html> <head> <title>Index</title> <scripts...> </head> <body> Hello <div id="content"></div> <button id="page1" value="page1"/> <but ...

How can we ensure that Protractor's ElementArrayFinder 'each' function pauses until the current action has finished before moving on to the next iteration?

Currently, I am facing an issue while trying to utilize an 'each' loop in my Angular 8 app's end-to-end tests using protractor. Within my page object, I have created a method that returns an ElementArrayFinder. public getCards(): ElementArr ...

Problem Alert: Click Event Not Functioning on Generated Links

Take a look at these two code snippets. Despite other jQuery functions in the same JS file working fine on the UL element, nothing seems to be happening with these. Is there something obvious that I am missing? <ul id="activityPaganation" class="paga ...

The data I am trying to obtain is not being returned by my hook as expected

I am trying to create a hook that fetches all properties from a database. The function I have is asynchronous, and when I call the hook in another function, it returns an empty array []. I understand that fetching data from the database is an asynchronous ...

The Angular 2 function within the subscribe method is being triggered before the request has finished processing

I have been attempting to extract a parameter from a URL and then passing it to another method. Below is the code snippet: ngOnInit() { this.getParamValues(); } getParamValues() { this.route.queryParams.subscribe(params => { ...

What is the significance of the "rc" within the version structure of an npm package?

Can someone help me understand what the rc in 2.2.0-rc.0 signifies? I'm curious if it indicates that this version is ready for production use. ...

Can you explain the functionality of this Sample AngularJS Infinite Scroll feature?

I stumbled upon this AngularJS script while searching for some samples, but I'm having trouble understanding the angular module and directive aspects of the code. However, I did manage to modify the loadMore() function to fetch a JSON resource from my ...

Encountering a type error with gatsby-plugin-dark-mode in a Typescript Gatsby setup

Issue with Layout warning in index.tsx when hovering: (alias) const Layout: ({ children }: Props) => JSX.Element import Layout Type '{ children: Element[]; }' is missing the following properties from type 'Props': theme, >toggle ...

Tips on retrieving a <list> from an MVC controller and passing it to the view with jQuery and AJAX

How can I retrieve a list from an MVC controller to a view using jQuery AJAX without getting the error message [object Object]? Here is my AJAX code: $.ajax({ type: 'POST', contentType: 'application/json; ch ...