【问题标题】:Incorrect value from event.value来自 event.value 的值不正确
【发布时间】:2021-01-21 06:20:21
【问题描述】:

我需要用角度材料格式化日期,所以我关注this guide:

我的代码在这个compoment.html:

<mat-form-field>
            <input id="datanint" formControlName="dataBirth" (dateChange)="emitBirthDateChangeForValidation($event)" matInput [matDatepicker]="picker" />
            <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
            <mat-datepicker #picker startView="multi-year" [startAt]="startDate"></mat-datepicker>

        </mat-form-field>

我的 ts:

const FORMAT = {
    parse: {
      dateInput: 'DD/MM/YYYY',
    },
    display: {
      dateInput: 'DD/MM/YYYY',
      monthYearLabel: 'MMM YYYY',
      dateA11yLabel: 'LL',
      monthYearA11yLabel: 'MMMM YYYY',
    }
  };


 providers:[
    {provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
    { provide: MAT_DATE_FORMATS, useValue: FORMAT }]
})


cosntructor(){
 this.dataBirth=new FormControl(moment());
}

     emitBirthDateChangeForValidation(event: any) {
            console.log(event);
            this.eventEmit.emit(event);
            }
        }

如果我刚刚链接的 stackblitz 项目以及当我在链接的项目中打印 event.value 时,我也会复制此代码(当它被称为数据更改时):

value: 2020-10-01T22:00:00.000Z

在我自己的项目中,当我打印 event.value 时(当它被称为数据更改时):

value: Moment {_isAMomentObject: true, _i: {…}, _isUTC: false, _pf: {…}, _locale: Locale, …}

我没有将 moment 对象放入 event.value 但我必须只有日期。谁能帮帮我?

【问题讨论】:

    标签: angular typescript angular-material momentjs angular-moment


    【解决方案1】:

    试试这个:

    import * as moment from 'moment';
    //your function
    emitBirthDateChangeForValidation(event: any) {
       console.log(moment(event.value._d).format("MM/DD/YYYY"));
    }
    

    一旦你得到正确的值,你就可以配置该数组来检索相关部分,就像我在上面的代码中以 MM/DD/YYYY 格式提取日期一样。

    PS:希望你已经完成了npm install moment --save

    【讨论】:

    • 是的,如果您想获得价值,您的解决方案很好,但我想了解为什么我们同时使用这两个时刻,解决方案相同但结果不同?
    • 如果没有看到您的实际代码,这很难说。甚至您共享的 stackblitz 链接也显示了默认内容,无需您进行编辑且没有任何日期更改。将需要 stackblitz 编辑和您在 stackblitz 上上传的实际代码。这个概念是 MatMomentDateModule 使用来自 moment.js 的时刻,并且类似地提取值。顺便说一下,我在代码中看到了问题,并如图所示进行了纠正。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-21
    • 2018-02-16
    • 2014-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    相关资源
    最近更新 更多