我试图根据使用 Angular Material 日期选择器选取的日期计算年龄,但出现错误。下面是我的代码:
HTML
<div class="input-container">
<mat-form-field>
<input matInput [matDatepicker]="dp" placeholder="Date of Birth" [(ngModel)]="birthdate" formControlName="firstCtrl">
<mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker #dp></mat-datepicker>
</mat-form-field>
<mat-form-field>
<input matInput placeholder="Age" value="{{age}}" [(ngModel)]="age" formControlName="firstCtrl" required>
</mat-form-field>
<button mat-button (click)="CalculateAge()">Calculate Age</button>
</div>
TS
export class ClaimSubmitComponent implements OnInit {
public birthdate: Date;
public age: number;
public CalculateAge(): void {
if (this.birthdate) {
var timeDiff = Math.abs(Date.now() - this.birthdate.getTime());
this.age = Math.floor(timeDiff / (1000 * 3600 * 24) / 365.25);
}
}
但我收到如下错误:
ERROR TypeError: this.birthdate.getTime is not a function
我究竟做错了什么?谢谢你!
将您的打字稿代码替换为以下代码。问题是 this.birthDate 在计算期间是字符串。我已经创建了示例应用程序,请查看堆栈闪电战 https://stackblitz.com/edit/angular-vcjume
export class ClaimSubmitComponent implements OnInit {
public birthdate: Date;
public age: number;
public CalculateAge(): void {
if (this.birthdate) {
var timeDiff = Math.abs(Date.now() - new Date(this.birthdate).getTime());
this.age = Math.floor(timeDiff / (1000 * 3600 * 24) / 365.25);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)