SNO
August 8, 2018, 12:30pm
1
I have a typescript class where one attribute is of type “date”. Now I’m searching for a clean solution to bind the date.
export class MyTestClass{
@bindable mydate: Date;
}
Following the template:
<template>
${typeof(mydate)}
<input type="text" value.bind="mydate | dateFormat: 'YYYY.Q' />
<template>
Referring to the example, the "${typeof(mydate)} always displays “string”. Is there any clever trick to bind that attribute so that the class directly converts the string to “Date” or do I need to do that in seperated steps?
Currently I need to parse all date-Attributes before saving:
this.MyTestClass.mydate = moment(this.MyTestClass.mydate).toDate();
You can use https://github.com/aurelia-contrib/aurelia-typed-observable-plugin
It has a custom observable
decorator which does automatic conversion.
Be careful with it though as two-way binding and update on change will not work correctly. You will need to use update on blur.
Or keep doing what you are currently…
2 Likes
@davismj I think you need to extend that into two-way value converter to meet @SNO ’s need.
I’m accepting commissions and PRs.
SNO
August 9, 2018, 8:57am
6
@davismj
I guess this doesn’t solve the issue. I already have the following value-converter:
export class DateFormatValueConverter {
toView(value, format) {
var formatted: string;
if (value == "" || value == undefined) {
return value;
}
formatted = moment(value, ["YYYY.Q", "MM.DD.YYYY", "YYYY.MM.DD", "YYYY.MM", "YYYY.M", "YYYYM"]).format(format);
if (formatted == "Invalid date") formatted = value;
return formatted;
}
}
But all the value-converter does is to format the value to a date string. Adding following snippet it does the same:
if (!(value instanceof Date)) {
value = new Date(value);
}
...
return date.toLocaleDateString();
The binded attribute type is still “string” instead of date. Or am I doing something wrong here?
Ah, I see. As CP said, you’ll need a fromView(dateString, format)
function on the value converter class that converts it back to a Date
.
1 Like
Your from view would be pretty simple I’d think.
const formats = ["YYYY.Q", "MM.DD.YYYY", "YYYY.MM.DD", "YYYY.MM", "YYYY.M", "YYYYM"];
export class DateFormatValueConverter {
toView(value, format) {
// [ ... stuff and things ... ]
}
fromView(value, format) {
return moment(value, formats).toDate();
}
}