当我们在 Angular 中使用日期选择器输入出生日期时如何显示年龄? (使用打字稿)

问题描述 投票:0回答:1

这是我的 HTML 代码, `

        <mat-form-field class="datepicker">
            <mat-label>Pick a date</mat-label>
            <input matInput 
                    #resultPickerModel="ngModel" 
                    [matDatepicker]="resultPicker" 
                    [(ngModel)]="date"
                    [min]="minDate" 
                    [max]="maxDate"
                     (input)="ageFromDateOfBirthday($event)">
            <mat-datepicker-toggle matSuffix [for]="resultPicker"></mat-datepicker-toggle>
            <mat-datepicker #resultPicker>
            </mat-datepicker>
            <mat-error *ngIf="resultPickerModel.hasError('matDatepickerParse')">
                "{{resultPickerModel.getError('matDatepickerParse').text}}"
                is not a valid date!
            </mat-error>
            <mat-error *ngIf="resultPickerModel.hasError('matDatepickerMin')">
                Minimum date should be {{minDate | date }}</mat-error>
            <mat-error *ngIf="resultPickerModel.hasError('matDatepickerMax')">
                Maximum date should be {{maxDate | date }}
            </mat-error>
        </mat-form-field>
    </mat-grid-tile>
    <mat-grid-tile>
        <mat-form-field appearance="fill" class="age">
            <mat-label>Age</mat-label>
            <input type="number" matInput >
        </mat-form-field>
    </mat-grid-tile>`

在这里,当我们在日期选择器中选择年龄时,我必须在输入文本框中提供AGE。 请让我知道任何解决方案。

html angular typescript angular-material
1个回答
4
投票

也许这段代码可以帮助你:

getAge(birthDate: Date): number {
    const ageTilNowInMilliseconds = Date.now() - birthDate.getTime();
    const ageDate = new Date(ageTilNowInMilliseconds);
    return Math.abs(ageDate.getUTCFullYear() - 1970); // Because computers count the today date from the 1st of January 1970
}

希望对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.