Bootstrap 在日期选择器元素中输入日期后,如何触发Angular 事件

jvidinwx  于 2022-12-07  发布在  Bootstrap
关注(0)|答案(3)|浏览(189)

我试图计算begindate和enddate之间的小时数并实时显示给用户,小时数应该自动计算并显示,而用户不必按按钮或类似的操作。现在,我尝试使用(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)
9q78igpj

9q78igpj1#

将更改事件绑定到输入并计算差值。

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

jhdbpxl92#

所以我有问题理解你的代码,但我看到一个特定的错误.你尝试过使用

<input (change)="computeLeave()".. />

mouseup可能无法在下面的此实现中工作

<input *ngIf= "!intraDay.checked" type="date" id="endDate" name="endDate" class="form-control"
           placeholder="02-02-2017" [(ngModel)]="leaveEndDate" formControlName="endDate" (mouseup)="computeLeave() />

另外,请注意,您没有在注解掉的代码段中调用函数。
如果这对你不起作用,你能在这里共享一个codepen,这样我就可以分叉和检查?

qcuzuvrc

qcuzuvrc3#

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

相关问题