0

I have a form which contains a date input.

The may enter a date in the format "DD MM YYYY" e.g. "25 12 2021".

However, in the form data/model, I'd like to convert that value into a different format: "2021-12-25".

Therefore the user sees one thing on screen, but the form data contains a reformatted version. Almost like the data gets converted before it gets added to the model, but the input still shows the original format.

Also, the other way around - the form model gets updated via patchValue or something like that, and then the format shown to the user is in the "DD MM YYYY" format.

E.g.

<!-- user has entered "25 12 2021" -->
<input value="25 12 2021" />

// it gets stored in the model as "2021-12-25"
form.value = { date: "2021-12-25" }

// form is updated form the class
form.patchValue({date: "1999-12-25"})

<!-- user see this in the put "25 12 1999" -->
<input value="25 12 1999" />

Is that possible?

I've created a blank Stackblitz to use as a playground if that's helpful.

shrewdbeans
  • 11,971
  • 23
  • 69
  • 115

1 Answers1

0

Update Another approach in this SO

imposible is nothing :)

create two functions (typical names are parse and format)

  parse(value:string) //receive in the way dd MM yyyy
                      // or in the way dd.MM.yyyy
                      // or in the way dd-MM-yyyy
  {

    value=value?value.replace(/[./-]/g," "):null
    const parts=value?value.split(' '):[];
    if (parts.length==3)
      return parts[2]+"/"+('00'+parts[1]).slice(-2)+"/"+('00'+parts[0]).slice(-2)
    
      return value
  }

  format(value:string) //receive in the way yyyy/MM/dd
  {
    const parts=value?value.split('/'):[];
    if (parts.length==3)
       return ('00'+parts[2]).slice(-2)+"-"+('00'+parts[1]).slice(-2)+"-"+parts[0]

    return value
  }

Then use a ngModel to change a formControl, use [ngModel] using the value of the formControl, and (blur) to change the value of the formControl -you can not use (ngModelChange) because the function is dispached each change of the input-

<form [formGroup]="form">
  <input
    #input
    [ngModel]="format(form.get('date').value)"
    (blur)="form.get('date').setValue(parse(input.value))"
    [ngModelOptions]="{ standalone: true }"
  />
</form>

See the stackblitz

NOTE: You can use the logic you want in the functions "parse" and "format"

Eliseo
  • 50,109
  • 4
  • 29
  • 67