Search code examples
angularangular-materialangular-formly

How to pass default value into material datepicker using formly?


I have problem with Angular 8 nad material and formly. I configured formlyField like this:

{
  key: 'releaseDate',
  type: 'datepicker',
  defaultValue: new Date(this.data.releaseDate.split('\\.')[2] + '.' + this.data.releaseDate.split('\\.')[1] + '.' + this.data.releaseDate.split('\\.')[0]),
  templateOptions: {
    label: 'data wydania',
    placeholder: 'Wpisz date wydania',
    required: true,
    datepickerOptions: {format: 'yyyy.MM.dd'},
    datepickerPopup: 'yyyy.MM.dd'
  }
}

I don't know how to pass default value to show view on chrome. What format should I use and what date should I pass into default value?


Solution

  • You have to pass a Date type: https://www.w3schools.com/js/js_dates.asp

    In this example, you set the current date as default value:

    {
      key: 'Datepicker',
      type: 'datepicker',
      defaultValue: new Date(),
      templateOptions: {
        label: 'Datepicker',
        placeholder: 'Placeholder',
        description: 'Description',
        required: true,
      },
    }
    

    In this example, you set the 24 December of 2018 as default value.

    {
      key: 'Datepicker',
      type: 'datepicker',
      defaultValue: new Date(2018, 11, 24),
      templateOptions: {
        label: 'Datepicker',
        placeholder: 'Placeholder',
        description: 'Description',
        required: true,
      },
    }