3

It's easy enough to interpalate a date with the date pipe: {{someDate | date}}

But is there an easy way do the same on an input field. Let's say I'm wanting to edit a user's birthdate, so I go to an edit form. The birthdate field says "1986-04-22T22:06:28.912Z" (the actual value returned from the database), rather than "Apr 22, 1986".

enter image description here

I can do things inside the component logic to get it to display how I'd like, but is there a way to use the date pipe on the value of an input?

sharpmachine
  • 3,783
  • 6
  • 19
  • 24

2 Answers2

1

I've been able to use the angular2-text-mask and text-mask-addons as a way to transform the format of input text field values. The documentation and related info is quite thorough and a date example can be seen on a text-mask demo page.

This ngconsultant blog post discusses a technique for adjusting input values using a somewhat limiting (browser-native focus/blur methods) @HostListener technique.

Keep in mind that if you are only interested in transforming the date for user UI convenience, you'll have to write additional code to revert the date to the prior format before storing or utilizing it, otherwise your data model will maintain the fancy formatted version rather than the original format.

(There is a very similar question answered regarding currency and a very basic solution is discussed in this stackoverflow post.)

Community
  • 1
  • 1
jmmygoggle
  • 921
  • 7
  • 18
0

There is no way to pass a string into the default angular date pipe, but you can create a custom pipe to do the work. This would allow you to keep the transformation logic out of your component, as well as give you reusable code that you can plug into any template.

    import {Pipe, PipeTransform} from '@angular/core'; 

    @Pipe({ 
        name: "dateFromString"
    })
    export class DateFromStringPipe implements PipeTransform {
        transform(dateString){

            //logic goes here to convert date string to readable format
            let readableDate = ...

            return readableDate;
        }
    }


Another option, if you do not want to handle generating the readable date string, would be for your custom pipe to return a date object, and you could then chain that pipe into the angular date pipe. In your template

unreadableDateString | customDatePipe | date
Alex Wheeler
  • 315
  • 2
  • 3