在这个 Angular 7 应用程序中,用户需要从日历输入中选择一个日期,然后生成 40 天前的日期。我无法在 Typescript 中弄清楚这一点。有很多 JavaScript 解决方案,但我不知道如何将它们转换为对 Angular 友好的打字稿版本。现在我有两个函数都试图做到这一点(生成 1 和生成 2),但都不起作用。
生成 1假设使用我导入的 'add-subtract-date' (npm),但我收到 Typescript 错误...“错误 TS2580:找不到名称 'require'。”
Generate 2没有错误,只是什么都不做。
我也不认为我的 HTML 是正确的。我对任何新想法持开放态度,请同时包含 HTML。
组件.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;
}
}
组件.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>