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

Troubleshooting: Why is my Datatables data not showing up with Angular 2/4 server side processing

Angular version 4.2.4 Angular-Datatables version 4.2.0 HTML Code Snippet <table datatable [dtOptions]="dtOptions"></table> Component Function ngOnInit() { this.dtOptions = { ajax: { url: "http://localhost:8880/nmets ...

Is React Context malfunctioning due to a syntax error?

Using the function "login" from React context is causing an error for me: const handleLogin = async (data: LoginType) => { try { await login(auth, data.email, data.password); router.push("/Dashboard"); } catch (error: an ...

Angular 2 with a jssor slider that adjusts seamlessly to different screen

After following the guidance provided in this answer on incorporating jssor into angular2, I have implemented the following JavaScript code snippet in a file and referenced it in angular-cli.json. jssor_1_slider_init = function() { var jssor_1_op ...

Transferring information to a deep-level interface

I am currently working on creating an object that aligns with my interface structure. Success Story export interface ServiceDataToDialog { id: number, service: string, } constructor(private _dialogRef: MatDialogRef<DialogServiceTabletAddRowComp ...

Encountering an issue with resolving parameters for the DecimalPipe in ngBootstrap/Angular2

Just delving into the world of Angular2 and trying to learn through hands-on experience. However, I've hit a roadblock! I attempted to import ng-bootstrap and encountered this error: https://i.stack.imgur.com/QDVJ3.png Here's my systemjs.config ...

What is the step-by-step process for implementing tooltips in Ant Design Menu after version 4.20.0?

According to the Ant Design documentation: Starting from version 4.20.0, a simpler usage <Menu items={[...]} /> is provided with enhanced performance and the ability to write cleaner code in your applications. The old usage will be deprecated in th ...

TypeScript: creating an interface property that relies on the value of another

Is it feasible to have an interface property that relies on another? For instance, consider the following: const object = { foo: 'hello', bar: { hello: '123', }, } I wish to ensure that the key in bar corresponds to the value of f ...

Issue with aliasing in tsconfig.app.json not functioning correctly in Angular 11

I'm facing a problem with aliasing after migrating my application to an Angular project. None of my imports are functioning properly with the ""@app"" alias. mainApp │ package.json │ tsconfig.json │ angular.json │ └─┠...

Is there a way to automatically extend my content to fill the space on the page below the Material UI AppBar?

I am currently using React and Material UI React to develop my application. My goal is to implement the AppBar component with content underneath, without causing the entire page to scroll. I want the content to occupy the maximum remaining height and the f ...

The function column.getHeaderGroupProps does not seem to be available

Struggling with the initial setup of react-table with typescript. I keep encountering an error related to the data passed into my table function: column.getHeaderGroupProps is not a function TypeError: column.getHeaderGroupProps is not a function at ht ...

Understanding the timing of records being returned via an Observable in Angular's ngOnInit

In my Angular 2 application, I am using an observable to keep track of an array of records. As the results of this observable are stored in the variable "records", I am utilizing *ngFor="let record of records" to iterate over and display them in my view. ...

Troubleshooting the excessive time taken for Angular Material tree re-rendering

I am currently using mat-tree with large data sets in child nodes retrieved from an API call, with each child node containing around 3k records. My approach involves updating the dataSource by adding the children from the API under the existing dataSource ...

Is there a way to run a node script from any location in the command line similar to how Angular's "

Currently, I am developing a node module that performs certain functions. I want to create a command similar to Angular's ng command. However, I am facing compatibility issues with Windows and Linux operating systems. Despite my attempts to modify the ...

Utilize the routerLink within a string value on a HashMap instance

I am currently storing translated parameters in a HashMap object on my component. However, I am facing an issue where certain attributes such as [routerLink] are not functioning properly or not being interpreted by Angular (v5). Here is the code snippet f ...

What is the reason that (click) does not send my data within <button>, while (change) within <input> does in Angular and HTML?

I am facing an issue while trying to send data to my Glassfish RESTful server. The method is activated successfully when I use (change) inside the input tag, but it doesn't work when I try using (click) or (change) to activate the method. I attempted ...

Leverage the power of InfiniteSWR in your project by integrating it seamlessly with

If you're looking for a comprehensive example of how to integrate useSWR hooks with axios and typescript, check out the official repository here. import useSWR, { SWRConfiguration, SWRResponse } from 'swr' import axios, { AxiosRequestConfig, ...

Displaying Angular reactive form data on screen and then populating it in a jQuery table

Successfully retrieving and displaying data from a template-driven form in Angular, however encountering difficulties when trying to achieve the same with a reactive form. The ultimate goal is to showcase this data on a jQuery table. ...

Issues with Angular's *ngIf directive not functioning correctly

Within my template, I have a block of HTML that controls the visibility of a div. <div *ngIf="csvVisible"> <p>Paragraph works</p> </div> This particular code snippet belongs to my component. export class SettingsComponent imple ...

Removing scrollbar from table in React using Material UI

I successfully created a basic table using react and material UI by following the instructions found at: https://material-ui.com/components/tables/#table. The table is functioning properly, but I am finding the scrollbar to be a bit inconvenient. https:// ...

Testing Angular - using observables that return varying values

I'm currently faced with the challenge of testing a component that subscribes to an observable in a service during its ngOnInit lifecycle hook. The component's behavior is expected to change based on the value received from the observable. To sim ...