簡體   English   中英

在datepicker元素中輸入日期后,如何觸發角度事件

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

我正在嘗試計算開始日期和結束日期之間的小時數,並將其實時顯示給用戶。 因此,如果同時輸入了開始日期和結束日期,則應該自動計算並顯示小時數,而無需用戶按下按鈕或類似操作。 現在,我正在嘗試使用(mouseup)事件來觸發計算,但是在endDate和startDate變量上調用getHours方法或getDate方法時,出現了未定義的錯誤。 這是有道理的,因為在觸發mouseup事件時,這兩個日期變量的值還沒有值。 我可以通過為startDate和endDate分配一個new Date()默認對象來解決此問題,但是一旦按下日期選擇器之一,它就會給出奇怪的輸出。 只要尚未將兩個日期選擇器都設置為一個值,輸出就必須保持為0。 那么我該怎么做呢? 請參閱下面的模板和組件。 處理工時計算的方法稱為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")
  }
}

繼承人我的模板

<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()"

將更改事件綁定到輸入並計算差異。

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

零件

  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;
    }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM