0

I'm trying to run one function - "createThreeDates()" that can generate three different results (dates based on -90, -60, -45), using the same variable. After a user sets a date in the input field, that date variable is set and used in the function. The Generate 1 button calls the function. Everything works fine if I only needed one date (not three). FYI, this function uses the installed/import package "add-subtract-date."

There are NO ERRORS in my code, but the function returns the SAME date (fortyDaysDate) to all three input fields in the browser (?). -I don't know how this is possible when I have different ngModels.

Here is 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, FormGroup } from '@angular/forms';


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

      public fortyDaysDate: any;
      public sixtyDaysDate: any;
      public ninetyDaysDate: any;



      private _retireSet: Date;
      @Input() set retireSet(date: Date) {
        this._retireSet = new Date(date);
      }

    constructor(private calculatorService: CalculatorService) { 
      }

      ngOnInit() {
      }

    public createThreeDates(): void {
      let d: Date = this._retireSet;
      let ninetyDaysBack = subtract(d, 90, "days");
      this.ninetyDaysDate = ninetyDaysBack;
  console.log('90 is ' + this.ninetyDaysDate);

        let sixtyDaysBack = add(d, 30, "days");
        this.sixtyDaysDate = sixtyDaysBack;
        console.log('60 is ' + this.sixtyDaysDate);

         let fortyDaysBack = add(d, 15, "days");
         this.fortyDaysDate = fortyDaysBack;
         console.log('45 is ' + this.fortyDaysDate);

// the value of sixtyDaysDate changes to fortyDaysDate value here...
         console.log('60 is ' + this.sixtyDaysDate);

        }
    }

    }

Here is component.html...

 <div class="container">
    <form class="ret-form" #calcForm="ngForm" novalidate (ngSubmit)="onSubmit(calcForm)">

    <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>
 <button type="button" class="btn btn-lg btn-outline-dark" (click)="createThreeDates()">Generate 1</button>      

    <div>
  <input type="text" name="RetireCalculatorDay90" value="ninetyDaysDate" ngModel #RetireCalculatorDay90="ngModel" 
  [(ngModel)]="ninetyDaysDate" class="form-control" />
    </div>

    <div>
  <input type="text" name="RetireCalculatorDay60" value="sixtyDaysDate" ngModel #RetireCalculatorDay60="ngModel" 
  [(ngModel)]="sixtyDaysDate" class="form-control" />
    </div>

  <input type="text" name="RetireCalculatorDay45" value="fortyDaysDate" ngModel #RetireCalculatorDay45="ngModel" 
[(ngModel)]="fortyDaysDate" class="form-control" />
    </div>


    </form>
    </div>
1
  • As a side note, you specify that getAllDates returns any, but you do not return anything. It should either be void or you should return something (and also not let that be an any). As for what you are doing, tslint (or other linter) would catch the variable shadowing (no-shadowed-variable). I'd say look at the compiled code and see what it is actually doing. Commented Oct 29, 2018 at 17:08

2 Answers 2

1

This is more of a code review than an answer. Your syntax is not correct here.

  • Remove the curly braces inside the function.
  • Make sure the function "subtract" is not mutating the variable passed in. You may want to "clone" the variable "_retireSet" so that you're not mutating it inside this function.
  • Use "const" if you're not reassigning the variable. In this function you are so you need to use "let".
  • As @crashmstr noted change the function return type to void

Side note: Function name is confusing. "getAllDates" this is implying you're returning an object with dates. Instead change the name to prepareAllDates or createAllDates or something similar.

Remember that "Set" and "Get" implies "Setting a Variable" and "Getting a Variable" respectively.

** Update ** From your comment below it looks like you're having an issue with javascript itself.

Assign By Value

var batman = 7;
var superman = batman;   //assign-by-value
superman++;
console.log(batman);     //7
console.log(superman); //8

Assign By Reference

var flash = [8,8,8];
var quicksilver = flash;   //assign-by-reference
quicksilver.push(0);
console.log(flash);        //[8,8,8,0]
console.log(quicksilver); //[8,8,8,0]

For your specific issue:

var x = new Date()

var y = new Date(x)

x.setFullYear('2019');

x //Date 2019-11-01T13:59:56.083Z
y //Date 2018-11-01T13:59:56.083Z
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks so much for your help here. Great suggestions on the function, it's working better now. I have not been coding very long, so I struggle with the correct syntax. I adjusted my code to reflect your suggested changes. I'm still having the strange Angular data-binding issue addressed in this post.
The function works, and I can console log the correct values, but at the end of the function, the "fortyDaysDate" value is returned to all three inputs in the view. When I break this into three different functions, the data-binding is correct in the view. So I know the ngModels work. The main variable (_retireSet) is changing in the function, but I don't know why that changes the three different variables on the ngModels (?). I will keep troubleshooting this.
Thanks again for the great advice. Finally got this working and posted correct code in a new answer, FYI. The function subtract was mutating the variable. Tried many things to lock that down, but could not. Having three ngModels on the set date, and three different get/set variables, was the only way I could get this to work.
0

After the advice I got on this post, here is the code that worked (FYI) resolving the issues.

component.HTML...

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

           <div><button type="button" class="btn btn-light" (click)="createThreeDates()">Calculate Dates</button> </div> 

    <div>
                <input type="hidden" name="RetireCalculatorDay90" value="ninetyDaysDate" ngModel #RetireCalculatorDay90="ngModel"
                [(ngModel)]="ninetyDaysDate" class="form-control" />
                <p class="textNinety"> 90 day notice is due {{ ninetyDaysDate | date: "longDate" }}. </p>
            </div>

     <div>
                <input type="hidden" name="RetireCalculatorDay60" value="sixtyDaysDate" ngModel #RetireCalculatorDay60="ngModel"
                [(ngModel)]="sixtyDaysDate" class="form-control" />
                <p>  60 day notice is due {{ sixtyDaysDate | date: "longDate" }}. </p>
            </div>   


     <div>
                <input type="hidden" name="RetireCalculatorDay45" value="fortyDaysDate" ngModel #RetireCalculatorDay45="ngModel"
                [(ngModel)]="fortyDaysDate" class="form-control" />
                <p> 45 day notice is due {{ fortyDaysDate | date: "longDate" }}. </p>
            </div> 

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, FormGroup } from '@angular/forms';


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

  public fortyDaysDate: any;
  public sixtyDaysDate: any;
  public ninetyDaysDate: any;
  public myRetDatePlus45: Date;
  public myRetDatePlus60: Date;
  public myRetDatePlus90: Date;

 private _retireSet: Date;
  @Input() set retireSet(date: Date) {
    this._retireSet = new Date(date);
    this.myRetDatePlus90 = this._retireSet;
  }

  private _retireSet60: Date;
  @Input() set retireSet60(date: Date) {
    this._retireSet60 = new Date(date);
    this.myRetDatePlus60 = this._retireSet60;
  }

  private _retireSet45: Date;
  @Input() set retireSet45(date: Date) {
    this._retireSet45 = new Date(date);
    this.myRetDatePlus45 = this._retireSet45;
  }


  constructor(private calculatorService: CalculatorService) { 
  }

  ngOnInit() {
  }



 public createThreeDates(): void { 
  let dNinety: Date = this.myRetDatePlus90;
  let ninetyDaysBack = subtract(dNinety, 90, "days");
  this.ninetyDaysDate = ninetyDaysBack;

 let dSixty: Date = this.myRetDatePlus60;
 let sixtyDaysBack = subtract(dSixty, 60, "days");
 this.sixtyDaysDate = sixtyDaysBack;
 console.log('60 is ' + this.sixtyDaysDate);

  let dForty: Date = this.myRetDatePlus45;
  let fortyDaysBack = subtract(dForty, 45, "days");
  this.fortyDaysDate = fortyDaysBack;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.