【问题标题】:material date picker always results in error with moment材料日期选择器总是导致时刻错误
【发布时间】:2018-12-07 06:50:41
【问题描述】:

不知何故,我无法将自定义日期格式应用于我的材料 Datepicker。我也尝试过以与在 Material Datepicker

由于我认为这过于复杂并且不起作用( 错误错误:Datepicker:值必须是 DateAdapter 识别的日期对象或 ISO 8601 字符串。而是得到:1525125600000)

我尝试使用来自this stack answerthis 参考实现。导致同样的错误。 它显然是将日期转换为时间戳,因此格式化字符串似乎按预期应用...... 另外我想知道为什么 angular 的实现会导致相同的错误(使用不同的时间戳,因为它使用当前日期作为开始位置)。问题是,我完全不知道在哪里寻找错误了

这是我的 .component.ts:

import {Component, Input, forwardRef} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {MatDatepickerInputEvent} from '@angular/material/datepicker';
import {default as _rollupMoment} from 'moment';
import * as _moment from 'moment';

const DATEMOMENT = _rollupMoment || _moment;

@Component({
  selector: 'custom-date-picker',
  templateUrl: 'app/components/datepicker/datepicker.component.html',
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => DatePickerComponent),
      multi: true
    }
  ]
})
export class DatePickerComponent implements ControlValueAccessor {

  private tecDateValue: string = '28.05.1994';
  @Input() public dateFormat: string = 'dd.MM.yyyy';
  @Input() public placeholder: string;

  @Input()
  public get dateValue() {
    return DATEMOMENT(this.tecDateValue, this.dateFormat);
  }

  public set dateValue(val) {
    this.tecDateValue = DATEMOMENT(val).format(this.dateFormat);
    this.propagateChange(this.tecDateValue);
  }

  public addEvent(type: string, event: MatDatepickerInputEvent<Date>) {
    console.log(event.value);
    this.dateValue = DATEMOMENT(event.value, this.dateFormat);
  }

  public writeValue(value: any) {
    if (value !== undefined) {
      this.dateValue = DATEMOMENT(value, this.dateFormat);
    }
  }

  private propagateChange = (val: any) => {
  };

  public registerOnChange(fn: any) {
    this.propagateChange = fn;
  }

  public registerOnTouched() {
  }
}

【问题讨论】:

    标签: typescript datepicker angular-material


    【解决方案1】:

    也许你可以在你的构造函数上设置 Locale.. 它对我有用

    constructor(private adapter: DateAdapter<any>) {
        this.adapter.setLocale('es');
    }
    

    希望有用:)

    【讨论】:

    • 这将导致仅使用默认日期格式。但是自定义日期设计仍然是不可能的。
    【解决方案2】:

    我找不到适合这个问题的解决方案。我避免这个问题的方法是隐藏日期选择器输入字段并使用库存材料,然后将输入分开。尽管这不是一个干净的解决方案,但它至少可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-09
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-13
      相关资源
      最近更新 更多