Linking a Date to a Kendo UI for Angular DatePicker Component

When attempting to bind to a Kendo UI Datepicker or Timepicker component, I encounter an error stating "The 'value' should be a valid JavaScript Date instance." Despite referencing a page in the Kendo Docs that addresses this issue, I am struggling to implement the solution in my specific case.

The server sends data that I store in my TypeScript object:

export interface Event {
  id: number;
  name: string;
  date: Date;
  startTime: Date;
  endTime?: Date;
}

During debugging, the values appear as follows in the TypeScript object:

id:1
name:"Event 1"
date:"2018-11-01T00:00:00"
startTime:"2018-11-01T08:30:00"
endTime:"2018-11-01T10:30:00"

Here is my component.ts file (if I use this.event = this.parse(data.event), the binding works without errors, but non-date fields are transformed into random dates from the parse function):

...

Below are snippets of how my components are structured in the .html file:

<kendo-datepicker [(value)]="event.date" id="date" name="date" style="width: 100%;" (valueChange)="handleChange($event)"></kendo-datepicker>

<kendo-timepicker [(value)]="event.startTime" id="startTime" name="startTime" style="width: 100%;" (valueChange)="handleChange($event)"></kendo-timepicker>

<kendo-timepicker [(value)]="event.endTime" id="endTime" name="endTime" style="width: 100%;" (valueChange)="handleChange($event)"></kendo-timepicker>

Answer №1

It appears that the reliability of the approach is questionable. The Date constructor can generate a date based on a number as milliseconds offset from 1970. Depending on how different browsers handle it, there may also be the possibility of creating a Date from the string "Event 1" (Chrome seems capable of this). Two potential solutions come to mind in this situation. One option is to attempt parsing the date string using a specific format:

private parseExact(json) {
    Object.keys(json).map(key => {
      const date = this.intl.parseDate(json[key], 'yyyy-MM-ddTHH:mm:ss');
      if (date) { json[key] = date; }
    });

    return json;
}

Alternatively, you could specify the fields that are dates:

private parse(json: any, dateFields: string[]) {
   for (let idx = 0; idx < dateFields.length; idx++) {
       const field = dateFields[idx]; 
       const value = json[field];
       if (value) {
         json[field] = new Date(value);
       }
   }

   return json;
}

https://stackblitz.com/edit/angular-1jujzo?file=app/app.component.ts

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered when trying to import Typescript file using a relative path

When attempting to execute src/index.js, I encountered the following error: Error: Cannot find module './utils/spinner' The import statement in index.js appears as follows: const { startSpinner, stopSpinner } = require('./utils/spinner&apos ...

How can I import a JavaScript file embedded in another project using ASP.Net?

I am currently working on two projects - a control library and my main project. In the control library, I am using a user control and some embedded CSS files. To use these CSS files in my main project, I am adding them from the PreRender event of my user c ...

Nested Promises in Angular's $q Library

I'm facing an issue with a function that should return a list of favorite locations. Here's the code snippet in question: When I call LocationsFactory.getFavoriteLocations(), it returns a promise like this: getFavoriteLocations: function() { ...

The JavaScript files were sourced from static files in APEX version 4.2.4

Can anyone help me locate the folder in the Oracle server where JavaScript files uploaded from Shared Components - Static Files are stored? I am currently using APEX version 4.2.4. ...

How can you retrieve the Adobe Marketing Cloud ID if cookies have not been set before using DTM?

Looking for a solution to capture the Adobe Marketing Cloud ID (MID) when a page loads using a Data Element or any other alternative method. The current Data Element logic works well if the Marketing Cloud cookie already exists. However, if there is no exi ...

I am looking to combine two arrays, potentially containing identical data

I have a task to combine two arrays, one from an API and the other from a database: Array1 (Data from API): { '0': { userid: 'kdkds', name: 'Stephan, email: '<a href="/cdn-cgi/l/email-protection" class="__cf ...

Can you describe the characteristics of emissive materials in three.js?

Currently, I'm delving into a basic demo using three.js and finding myself perplexed by the way THREE.MeshPhongMaterial behaves, especially since I come from a background working with the Unity Game Engine. create_ring() { // creates a ring mesh ...

Exploring through an array: Error encountered - Unable to access property as it is undefined

As a novice coder, I'm seeking assistance with a basic issue that has me stumped despite my attempts to find a solution. My grid consists of arrays nested within an array named 'cells', filled with 1s and 0s representing live and dead cells. ...

I am unable to npm install on a cloned ngx-datatable repository

Hello everyone! After observing for quite some time, I have finally decided to ask a question and share it with the community for the benefit of others. When I clone certain projects and run npm install (even from my work's gitlab), everything works ...

Having trouble retrieving a path reference from Firebase Storage using getDownloadURL() in React Native?

I am having trouble uploading some images and retrieving them using the .getDownloadURL() method. Oddly enough, it works perfectly fine in another part of my application when I update the user's profile picture, but for some reason, it fails in the co ...

It appears that the .fadeOut() function is not working properly when applied to an image

I want my input text box to automatically submit the form and display a checkmark image after the user has been idle from typing. I tried implementing a fadeout function for the image but it doesn't seem to be working. var timer = null; $('.form ...

The command 'ng' for Angular is not being detected as a valid internal or external command, executable program, or batch file, preventing access to the Angular app from outside the localhost

Whenever I try to run "'ng' is not recognized as an internal or external command, operable program or batch file." with ng serve --host 0.0.0.0 from my command prompt, it gives me this error message. However, running it through the node.js comma ...

Manipulating values within a multidimensional array using JavaScript

I am attempting to populate a multidimensional array with data from a JSON file. The issue I am facing is that I am unable to update the content in the array: if(j>i && hoursYy == hoursY && secondsX == secondsXx){ wocheArray[i].count = wocheArray[i] ...

Restriction on Google Maps API: Mouseover functionality is limited to specific hours of the day

Throughout my programming journey, I've encountered some weird errors, but this one takes the cake. I'm stumped as to why it's happening. Here's the situation: My application is supposed to fetch data from a MySQL Database and display ...

Issue with Angular not functioning properly in IE 11 across both production and development builds

After updating my global angular-cli version to 8, I encountered an error in IE11 when building my project in production mode. Interestingly, the project works fine in Chrome. The error message for the production version is as follows: https://i.sstatic. ...

Disseminate several outcomes using a Discord bot

My first experience using stackoverflow was to seek help regarding a bot created to post results whenever a new episode of a show in the search list is added on nyaa.si. The issue I'm facing is that the bot posts the same episode multiple times within ...

Obtaining information from AngularJS callback function in loopback: A comprehensive guide

I am trying to figure out how to retrieve the "good" array from an angular function. Here is the function I have in my Angular code: app.run(function($rootScope,Communications,$http,$filter) { $rootScope.getCommunication = function(object_type ...

Develop a TypeScript project in React that incorporates a dynamic country flag component

Hi there! I've been diving into the world of using React with TypeScript recently, and I came across a package called "react country flag" that I wanted to use for displaying country logos. However, I'm running into issues trying to use it with T ...

Issues arising from the event target

What is the reason behind this code functioning successfully only when the alert function is called? The color changes after closing the alert box, but if the line with the alert command is commented out, nothing happens. function setLinkColor(el) ...

Ensure that children elements are aligned to the bottom by setting the axis of the HTML

Elements positioned within a parent DIV typically flow from top to bottom. Even when using Javascript to add elements to the parent DIV, they maintain this top-to-bottom positioning. I am interested in achieving a bottom-to-top axis alignment within the pa ...