从Angular 6 + Angular Material中计算日期开始的年龄

时间:2018-11-02 05:32:17

标签: angular

我正在尝试从日期计算年龄,并使用Angular Material日期选择器进行了选择,但出现错误。下面是我的代码:

HTML

<div id="container">
<div class="cell"  ></div>
<div class="cell"  ></div>
</div>

TS

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

但是我收到类似这样的错误:

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

我在做什么错?谢谢!

1 个答案:

答案 0 :(得分:0)

用以下代码替换您的打字稿代码。问题是this.birthDate在计算期间是字符串。我已经创建了示例应用程序,请检查stackblitz

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