简体   繁体   中英

Angular material date picker return Moment object instead of Date

I have a strange problem, in my html I defined-

    <mat-radio-button value="embargoed">
        <div>Everyone, limited by date</div>
        <mat-form-field *ngIf="data.selected === 'embargoed'">
            <mat-label>Available from date</mat-label>
            <input matInput [matDatepicker]="picker" #input [(ngModel)]="date">
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <mat-datepicker #picker></mat-datepicker>
        </mat-form-field>
    </mat-radio-button>

in my comonent I initialized-

date = new Date();

I have an OnSubmit function that does-

onSubmit(){
    if (this.data.selected === 'embargoed') {
        this.data.date = this.date;
    }
}

In debud I can see that this.date is a Moment object instead of a Date object, any idea why?

I found the reason. In my app.module.ts I had declared:

 {provide: MAT_DATE_FORMATS, useValue: MAT_MOMENT_DATE_FORMATS}

From https://material.angular.io/components/datepicker/overview :

The type of values that the datepicker expects depends on the type of DateAdapter provided in your application. The NativeDateAdapter, for example, works directly with plain JavaScript Date objects. When using the MomentDateAdapter, however, the values will all be Moment.js instances.

Also: https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings :

The datepicker was built to be date implementation agnostic. This means that it can be made to work with a variety of different date implementations. However it also means that developers need to make sure to provide the appropriate pieces for the datepicker to work with their chosen implementation.

this.date = new Date(this.date);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM