Calculate the date input in Angular 7 by subtracting calendar days

As a user of this Angular 7 application, you are required to choose a date from a calendar input and then determine what day it was 40 days ago. Unfortunately, I have not been able to accomplish this in Typescript yet. There are numerous JavaScript solutions available, but I am struggling to convert them into an Angular-compatible typescript version. Currently, I have two functions attempting to achieve this (Generate 1 & Generate 2) both without success.

Generate 1 is supposed to utilize the 'add-subtract-date' library I imported via npm, but I keep encountering the Typescript error... "error TS2580: Cannot find name 'require'."

Generate 2 does not throw any errors but also fails to perform the desired action. Moreover, I suspect there might be issues with my HTML implementation as well. Any fresh ideas on how to tackle this issue would be greatly appreciated, just remember to include modifications to the HTML as part of your solution.

component.ts...

import { Component, EventEmitter, Input, Output, OnInit } from '@angular/core';
import { CalculatorService } from '../calculator.service';
import { add, subtract } from 'add-subtract-date';
import { NgForm } from '@angular/forms';


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  lastWorkingDay: any;
  isWeekday: string;

  public fortyDaysDate: any;



    private _retireSet: Date;
   get retireSet(): Date {
    return this._retireSet;
   }
   set retireSet(value: Date) {
    this._retireSet = value;

  }


  constructor(private calculatorService: CalculatorService) { 
  } 

  ngOnInit() {

  }


//Generate 1, this worked when using "const d: Date = new Date()"
public daysForty(): any {
  const d: Date = this.retireSet;
  const fortyDaysBack = subtract(d, 40, "days");
  this.fortyDaysDate = fortyDaysBack; 
}


// Generate 2, this does not work
  protected generateLastWorkingDay(): Date {
    const lastWorkingDay = new Date(Date.now()); 
    while(!this.isWorkingDay(lastWorkingDay)) {
      lastWorkingDay.setDate(lastWorkingDay.getDate()-40);
    }    
    return lastWorkingDay;
  }    
  private isWorkingDay(date: Date) {
    const day = date.getDay();
    const isWeekday = (day > 0 && day < 6);
    return isWeekday; 
  }





}

component.html...

  <form>
        <div class="container">

        <div class="form-group">
            <label for="retireSet">Set Date</label>
            <input type="datetime-local" id="retireSet" 
      name="RetireCalculatorSetDate" value="retireSet" ngModel 
      #RetireCalculatorSetDate="ngModel" [(ngModel)]="retireSet" class="form-control" />
        </div>

        <div class="form-group">
            <label for="staffID">Staff ID</label>
            <input type="text" id="staffID" name="RetireCalculatorStaffID"
                   [(ngModel)]="RetireCalculatorStaffID" 
                class="form-control" /> 
</div>


        <div>
                <button type="button" class="btn btn-success"
                        (click)="daysForty()">Generate 1</button>       
                <input type="text" name="RetireCalculatorDay45" value="fortyDaysDate" ngModel #RetireCalculatorDay45="ngModel" 
                [(ngModel)]="fortyDaysDate" class="form-control" />        
        </div>

        <div>
            <button type="button" class="btn btn-success" (click)="generateLastWorkingDay()"> Generate 2 </button>    
            <input type="date" class="text-field w-input" name="LastWorkingDay" 
                   value="LastWorkingDay" [(ngModel)]="LastWorkingDay" />
        </div>


        <button type="button" class="btn btn-success"  (click)="sendForm($event)">Submit</button>

        </div>
        </form>

Answer №1

It seems like there is a mistake in how you are using the import statement. Just a reminder that when importing, you should be bringing in functions, not objects.

import { add, subtract } from 'add-subtract-date';
...

// Function to generate 30 days ago
public thirtyDaysAgo(): Date {
  const currentDate: Date = new Date();
  const thirtyDaysBack = subtract(currentDate, 30, "days"); // Make sure to verify if the subtract() function modifies "currentDate" or returns a new date
  return thirtyDaysBack;
}

The second function you have defined is a bit unclear. The function name suggests it should provide the LastWorkingDay, but the logic involving the while loop may need further clarification.

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

Why does TypeScript assign parameters in the opposite direction when assigning callbacks?

When a function is called with an argument, the argument type is matched to the parameter type. This means that the argument type must be the same as, or more specific than, the parameter type. For example: const foo = (bar: string | number) => { con ...

Discrepancies in ESLint outcomes during React app development

As a newcomer to React development, I am encountering discrepancies between the errors and warnings identified in my project's development environment versus its production environment. Strangely, I have not configured any differences between these en ...

Building AngularJS directives using CSS classes

My current approach is as follows: class AService { $http: any; $state: any; static $inject = ['$http', '$state']; constructor($http, $state) { this.$http = $http; this.$state = $state; }; Dealing w ...

Difficulty rendering images and CSS during preloading in a Node.js environment

I'm aware of the necessity to use a middleware, but I need guidance on how to implement it correctly. Here is the snippet of code I currently have: const prerender = require('prerender'); var server = prerender({ chromeFlags: ['--no-s ...

Validation of emails in Angular through the utilization of reactive forms

Hello there, I'm new to Angular and looking for some assistance. Specifically, I am currently working on validating an email input using a reactive form with the keyup event. registerform:any; ngOnInit(): void { this.registerform = new F ...

The error message "Property 'DecalGeometry' is not found in the type 'typeof "..node_modules/@types/three/index"'."

Within my Angular6 application, I am utilizing 'three.js' and 'three-decal-geometry'. Here is a snippet of the necessary imports: import * as THREE from 'three'; import * as OBJLoader from 'three-obj-loader'; import ...

Struggling to retrieve posted data using Angular with asp.net

I have encountered an issue while sending a post request from Angular to my ASP.NET server. I am trying to access the values of my custom model class (SchoolModel) and I can see that all the values are correct inside Angular. However, when I attempt to ret ...

Exploring the relationship between Typescript, RxJS, Ajax, undefined values

This particular question stands out due to the fact that despite similar issues being previously addressed, none of the existing solutions have proven effective. The problem at hand is as follows: There's a Typescript class that initiates an RxJS.aja ...

Refreshing Angular 2 + Firebase app causes user to be logged out

Just diving into Angular2, Firebase, and SPAs for the first time. I've been tasked with enhancing a Angular2 (with Firebase email&pw auth) application by adding some new features. The app primarily consists of a blog (main page), a shop (/shop), a ...

What is the best way to arrange and manage assets?

I created a component with an image in it. The current file structure is like this: https://i.sstatic.net/hkZWG.png Now, my query is whether placing the assets folder inside the web folder is the right choice or not? UPDATE This is what I tried: impor ...

Creating dynamic tags based on values is a straightforward process that involves identifying key variables

Looking to create a template that can dynamically define native HTML tags based on a variable value. I attempted using a custom directive to swap out the initially defined tag with the desired new one, similar to what is discussed here. While this approac ...

unable to call a function within Angular

To create a dynamic menu, I am utilizing primeng's menu panel. Firstly, I declare my item variable: items: MenuItem[]=[]; I have two JavaScript objects to incorporate into the menu, namely groupsItem and ejsItem. Here is their structure: groupsI ...

Angular 7 - Creating tooltips with multiline text

I've utilized template strings to create a multi-line string. toolTip = ` ${Test} : ${number} ${Test} : ${number} ${Test} : ${number} ${Test} : ${number} ${Test} : ${number}}`; The issue I'm facing is that w ...

Once the user logs out, they have the ability to navigate back using the back button. What steps can be taken to address this

route.ts const appRoutes: Routes = [ { path: '', redirectTo: 'login', pathMatch: 'full' }, { path: 'login', component: LoginComponent }, { path: 'dashboard', canActiva ...

Implementing Typescript with React: Assigning event.target.name to state

I am facing an issue with a React state that has specific named keys defined in an interface... Despite trying a potential solution based on the state keys, I am still encountering an error... { [x: string]: string; }' provides no match for the sign ...

Mastering the art of leveraging generics in conjunction with ngrx actions

Currently, I am in the process of developing an Angular 7 application that utilizes the NGRX store. In our application, we have numerous entities, each with its own dedicated list view. I decided to explore using generics with the NGRX store to avoid writi ...

In order to emphasize the chosen list item following a component refresh

SCENARIO: Let's consider a scenario where I have a component named list, responsible for displaying a list of all customers. Within this list, certain conditions are set up as follows: 1) Initially, the 1st list-item (e.g. Customer 1) is selected by ...

Using TypeScript for abstract methods and polymorphism

What do I need to fix in order for this code to function properly? abstract class Animal { // No constructor ... public abstract me():Animal; } class Cat extends Animal { constructor() { super(); } // Why does this no ...

Creating alignment within a form/

These two elements inexplicably gravitate towards the edge of the page. Is there a specific reason for the suitcase (only log and pass)? <div class="control-group" ng-class="{true: 'error'}[submitted && form.log.$invalid]"> & ...

Developing a Gulp buildchain: Transforming Typescript with Babelify, Browserify, and Uglify

I've configured a buildchain in Gulp, but when I execute the gulp command, it only utilizes one of the two entry points I specify. My goal is to merge the methods outlined in these two resources: and here: https://gist.github.com/frasaleksander/4f7b ...