I created a Custom Element – a calendar view date picker that allows you to pick multiple non-contiguous days. I designed the Custom Element to work with a @bindable
property of type Date[].
However, the data that I’m receiving from the server lists dates as a comma-separated list of string. (e.g. “02-03-2020,02-04-2020,…”)
So, I thought I’d use a value converter to try to convert the string into a Date[] and back. However, what I’ve tried isn’t working – the original string (in the view model) never gets updated when changes are made to the Date[] (in the custom element).
I’m a little confused as to how/when the “conversion” takes place and what that means in terms of what is actually being passed to and from my custom element.
Here is the basics of what I have:
value converter
import * as moment from "moment";
export class DateListValueConverter
{
public toView(value : string)
{
if(!value) return [];
let temp = string.split(",");
return temp.map(d => new Date(d));
}
public fromView(value : Date[])
{
if(!value) return "";
let temp = value.map(d => moment(d).format("MM-DD-YYYY"));
return temp.toString();
}
}
date picker custom element
export class DatePickerCustomElement
{
@bindable({defaultBindingMode: bindingMode.twoWay })
public selectedDates : Date[] = [];
...
public selectDateClick(date: DateItem, e: MouseEvent)
{
if(!e.ctrlKey) //If user doesn't CTRL + Click
{
this.selectedDates = [];
//This push does not trigger value converter
this.selectedDates.push(date.date);
}
else
{
let index = this.selectedDates
.findIndex(d => moment(d).isSame(date.date, 'day'));
if(index < 0)
this.selectedDates.push(date.date);
else
//This splice does not trigger value converter
this.selectedDates.splice(index,1);
}
}
view model
export class Example
{
public myDates : string = "02-03-2020,02-05-2020";
...
}
view
<date-picker selected-dates.bind="myDates | dateList"></date-picker>
If I do the following:
view model
export class Example
{
public myDates : string = "02-03-2020,02-05-2020";
public dateList : Date[] = [];
activate()
{
this.dateList = this.myDates.split(",").map(d => new Date(d));
}
}
view
<date-picker selected-dates.bind="dateList"></date-picker>
Then the data-binding actually works and the push
and splice
in the date-picker
element actually cause an update to the property in the vm.
Is there a way to get this working with a value converter?