2017-01-22 19 views
1

2つのテキストボックスがあります。 1つのテキストボックスはユーザーからの生年月日を受け取り、生年月日に基づいて計算し、別のテキストボックスに年齢を表示します。生年月日から年齢をタイプ2を使って計算するには

ここに私のコンポーネントクラスが

Student.component.html

<div class="row"> 
<div class="input-field col m2"> 
    <input type="date" id="txtdate"> 
</div> 
<div class="input-field col m4"> 
    <input type="number" id="age"> 
</div> 

student.component.ts

import { Component, OnInit } from '@angular/core'; 

@Component({ 
selector: 'stud', 
templateUrl: './student.component.html' 
}) 
export class StudentComponent implements OnInit 
{ 

    constructor() { } 

    ngOnInit() { } 

} 
function CalculateAge() 
{ 
    var birthdate = <HTMLElement>document.getElementById("txtdate"); 
    var dt = new Date(); 
    var today = dt.getDate(); 

} 

私はどのようにcalculatんです生年月日からの年齢?

+0

のvalueOfを使用してみてください:VAR差= today.valueOf() - birthdate.valueOf(); – darron614

答えて

0
<div class="row"> 
    <div class="input-field col m2"> 
     <input type="date" [(ngModel)]="birthdate" id="txtdate"> 
    </div> 
    <div class="input-field col m4"> 
     <input type="number" [(ngModel)]="age" id="age"> 
    </div> 
    <button (click)="CalculateAge()">Calculate Age</button> 
</div> 

そして、あなたのコンポーネントで

import { Component, OnInit } from '@angular/core'; 
@Component({ 
selector: 'stud', 
templateUrl: './student.component.html' 
}) 
export class StudentComponent implements OnInit 
{ 
    public birthdate: Date; 
    public age: number; 

    constructor() { } 

    ngOnInit() { } 

    public CalculateAge(): void 
    { 
     if(this.birthdate){ 
      var timeDiff = Math.abs(Date.now() - this.birthdate); 
      //Used Math.floor instead of Math.ceil 
      //so 26 years and 140 days would be considered as 26, not 27. 
      this.age = Math.floor((timeDiff/(1000 * 3600 * 24))/365); 
     } 
    } 

} 
+1

これは機能しません。計算ボタンをクリックすると、コンソールでエラーが表示されます。 "birthdate.getTimeは関数ではありません"。代替品を提案してください – Maximum

+0

@ Maxax私はそれを更新しました、今試してみてください! –

+3

私はまだこの行でいくつかの問題に直面しています "var timeDiff = Math.abs(Date.now() - this.birthdate);"私はthis.birthdateエラーでエラーを表示しています: "算術演算子の右辺は任意の数字または数字でなければなりません" – Maximum

関連する問題