简体   繁体   中英

How do i trigger an event in angular after a date has been entered in datepicker element

I am trying to calculate the hours between a begindate and an enddate and show this to the user in realtime. So if both begindate and enddate have been entered, the hours should be calculated and presented automatically without the user having to press a button or something like this. Right now i'm trying to use the (mouseup) event to trigger the calculation but I get a not defined error when i'm calling getHours method or getDate method on the endDate and startDate variables. This makes sense because the values of these 2 date variables don't have a value yet when the mouseup event is triggered. I could circumvent this problem by assigning a new Date() default object to startDate and endDate but that gives strange output as soon as I press one of the datepickers. The output needs to remain 0 as long as both datepickers haven't been set a value yet. So how do I do this? See my template and component below. The method that is handling the hours calculation is called computeLeave()

import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {AccountService} from "../../account/account.service";

@Component({
  selector: 'app-leave-create',
  templateUrl: './leave-create.component.html',
  styleUrls: ['./leave-create.component.css'],
  providers: [AccountService]
})
export class LeaveCreateComponent{
   title: string;
   leaveCreateForm: FormGroup;
  leaveRemaining: [number, number];
  leaveRemainingTotal: number;
  leaveRequested: [number, number];
  leaveRequestedTotal: number = 0;
  leaveRequestedStatutory: number = 0;
  leaveRequestedNonstatutory: number = 0;
  private leaveHours: [number, number];

  leaveStartDate: Date; //= new Date();
  leaveEndDate: Date; //= new Date();

  constructor(private readonly fb: FormBuilder,
              private accountService: AccountService) {
    this.title = 'Verlofuren aanvragen';
    this.leaveCreateForm = fb.group({
      startDate: ['', [Validators.required]],
      endDate: ['', [Validators.required]],
    });
    this.leaveHours = [180, 120];
  }

  // ngOnInit(): void {
  //   console.log("oninit called")
  //   this.computeLeave();
  // }

  // ngOnChanges(): void{
  // console.log("changing")
  //   this.computeLeave();
  // }


  onSubmit() {
    // console.log(localStorage.getItem('account').toString())
    // this.accountService.grantLeaveHours(this.leaveCreateForm.get('startDate').value, this.leaveCreateForm.get('endDate').value, JSON.parse(localStorage.getItem("account")))
    console.log('%s: startDate=%s, endDate=%s',
      this.constructor.name,
      this.leaveCreateForm.get('startDate').value,
      this.leaveCreateForm.get('endDate').value
    );
  }

  // onReset() {
  //   this.leaveCreateForm.reset();
  //   this.computeLeave();
  // }

  private computeLeave() {
    console.log("computeLeave called..")
    //console.log("test" + this.leaveCreateForm.get('startDate').value.toString())
    //this.leaveStartDate = new Date(this.leaveCreateForm.get('startDate').value);
    //this.leaveEndDate = new Date(this.leaveCreateForm.get('endDate').value);
    // console.log("Startdate: " + this.leaveStartDate.toString())
    // console.log("EndDate: " + this.leaveEndDate.toString())
    if (this.leaveStartDate === undefined || this.leaveEndDate === undefined) {
      this.leaveRequestedTotal = 0;
      this.leaveRequestedStatutory = 0;
      this.leaveRequestedNonstatutory = 0;
    }

    if(this.leaveStartDate.getDate() !== this.leaveEndDate.getDate()) {
      console.log("Startdate: " + this.leaveStartDate.toString())
      console.log("EndDate: " + this.leaveEndDate.toString())
      console.log("not undefined")
      console.log("hour" + this.leaveStartDate.getHours())
      console.log("hour" + this.leaveEndDate.getHours())
      this.leaveRequestedTotal = this.leaveStartDate.getHours() + this.leaveEndDate.getHours();
      this.leaveRequestedStatutory = this.leaveRequestedTotal * 0.8;
      this.leaveRequestedNonstatutory = this.leaveRequestedTotal * 0.2;
    }
    else console.log("undefined")
  }
}

Heres my template

<h2>{{title}}</h2>
<form [formGroup]="leaveCreateForm" (ngSubmit)="onSubmit()">
  <div class="row">
      <div class="col-sm-4 form-group">
        <label for="startDate">Begin datum</label>
        <!--<input type="datetime-local" id="startDate" class="form-control"-->
               <!--placeholder="01-01-2017" [(ngModel)]="leaveStartDate" formControlName="startDate"-->
               <!--(mouseup)="computeLeave()">-->
        <input type="date" id="startDate" name="startDate" class="form-control"
               placeholder="01-01-2017" [(ngModel)]="leaveStartDate" formControlName="startDate" (focus)="computeLeave()">
      </div>
    <div class="col-sm-4 form-group">
      <label class="form-check-label">
        <input #intraDay class="form-check-input" type="checkbox" (change)="0">
        Verlof duurt minder dan 1 dag
      </label>
      <input *ngIf= "intraDay.checked" type="text" class="form-control" placeholder="voer het aantal uren in" formControlName="intraDayHours">
    </div>
  </div>
  <div class="row">
  <div class="col-sm-4 form-group">
    <label *ngIf= "!intraDay.checked" for="endDate">Eind datum</label>
    <input *ngIf= "!intraDay.checked" type="date" id="endDate" name="endDate" class="form-control"
           placeholder="02-02-2017" [(ngModel)]="leaveEndDate" formControlName="endDate" (mouseup)="computeLeave()">
  </div>
  </div>
  <div class="form-group">
    <table class="table">
      <thead>
      <tr>
        <th>Type</th>
        <th>Berekend</th>
        <th>Beschikbaar</th>
      </tr>
      </thead>
      <tbody>
      <tr>
        <td>Wettelijk</td>
        <td>{{leaveRequestedStatutory | number:"1.0-0"}}</td>
        <!--<td>{{leaveRemaining[0] | number:"1.0-0"}}</td>-->
      </tr>
      <tr>
        <td>Bovenwettelijk</td>
        <td>{{leaveRequestedNonstatutory | number:"1.0-0"}}</td>
        <!--<td>{{leaveRemaining[1] | number:"1.0-0"}}</td>-->
      </tr>
      <tr>
        <td>Totaal</td>
        <td>{{leaveRequestedTotal | number:"1.0-0"}}</td>
        <!--<td>{{leaveRemainingTotal | number:"1.0-0"}}</td>-->
      </tr>
      </tbody>
    </table>
  </div>
  <div class="form-group">
    <button type="submit" class="btn btn-default">Aanvragen</button>
    <button type="button" class="btn btn-default" (click)="onReset()">Reset</button>
  </div>
</form>

ERROR TypeError: this.leaveStartDate.getDate is not a function
    at LeaveCreateComponent.webpackJsonp.../../../../../src/app/app/leave/create/leave-create.component.ts.LeaveCreateComponent.computeLeave (leave-create.component.ts:74)
    at Object.eval [as handleEvent] (LeaveCreateComponent.html:24)
    at handleEvent (core.es5.js:11998)
    at callWithDebugContext (core.es5.js:13467)
    at Object.debugHandleEvent [as handleEvent] (core.es5.js:13055)
    at dispatchEvent (core.es5.js:8614)
    at core.es5.js:10770
    at SafeSubscriber.schedulerFn [as _next] (core.es5.js:3647)
    at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
    at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.next (Subscriber.js:185)

如果您使用ngModel将日期选择器的数据绑定到模型,则应尝试使用ngModelChange事件计算日期差,例如: (ngModelChange)="computeLeave()"

Bind change event to the input and compute difference.

<input type="date" id="startDate"  name="startDate" [(ngModel)]="leaveStartDate" (change)="onChange($event)">
<input type="date" id="endDate" name="endDate" [(ngModel)]="leaveEndDate" (change)="onChange($event)">

component

  isValidDate(date:any){
    let checkDate: any = new Date(date);
    return checkDate != "Invalid Date";
  }

  onChange(value){
    if(this.leaveStartDate && this.leaveEndDate && this.isValidDate(this.leaveStartDate) && this.isValidDate(this.leaveEndDate)) {
       //custom logic goes here
       //this.leaveRequestedTotal = moment.duration(this.leaveEndDate.diff(this.leaveStartDate));
    } else {
      this.leaveRequestedTotal = 0;
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM