What is the process for connecting a date/time form control?

My code seems to only be working for the 'title' element, while the 'docdatetime' control remains blank. Can anyone spot what I'm doing wrong?

//template ===================================================
<div class="form-group">
  <input type="text" id="title" formControlName="title" class="form-control">
</div>

<div class="form-group">
  <input type="datetime-local" id="docdatetime" formControlName="docdatetime" class="form-control">
</div>

//component.ts ===============================================
import { FormGroup, FormControl } from '@angular/forms';
..... 

export class..... 
    docForm: FormGroup;

    ngOnInit() {
        let docTitle = 'My first document';
        let docDate = 'Jun 15, 2015, 9:43:11 PM';
        this.docForm = new FormGroup({
            'title': new FormControl(docTitle),
            'docdatetime': new FormControl(new Date(docDate))
        });
    }   

https://i.sstatic.net/zlwym.jpg

Answer №1

To troubleshoot this issue, it is important to note that the DatetimeLocal property on the input has a specific format requirement of YYYY-MM-DDTHH:MM:SS.SSS, known as an ISO Date format. However, in reality, an ISO Date's format includes a Z for the timezone, indicating zero UTC offset. You can visit this link for details on ToISOString(). A simple solution would be to remove the last character, usually a Z, from new Date().toISOString().

let docTitle = 'My first document';
let docDate = 'Jun 15, 2015, 21:43:11 UTC'; //Ensure to convert to UTC for date accuracy.
this.docForm = new FormGroup({
    'title': new FormControl(docTitle),
    'docdatetime': new FormControl(new Date(docDate).toISOString().slice(0, -1))
});

IMPORTANT

Take into consideration that the value retrieved from the input will not be an actual Date, but a string instead. If you require it to be a date later on, remember to create a new Date() object using the string value.

Answer №2

One suggestion is to include the following lines in the ngOnInit section:

this.docForm.controls['docTitle'].setValue('My initial document');
this.docForm.controls['docDate'].setValue('June 15, 2015, 9:43:11 PM');

Answer №3

Dealing with a similar issue, I managed to resolve it by converting the date/time format prior to transmitting it to the server.

For instance (UTC Brazil):

If you input "15/12/2020 22:30:00"

The output will be: '2020-12-16T01:30:00.000Z'

To perform the conversion, use the following code snippet:

var date = new Date('2020-11-06T01:30:00.000Z');
console.log(date.toLocaleDateString());
console.log(date.toLocaleString());
console.log(date.toLocaleTimeString());

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

What is the best way to pass an array as a parameter in Angular?

I have set up my routing module like this: const routes: Routes = [ { path: "engineering/:branches", component: BranchesTabsComponent }, { path: "humanities/:branches", component: BranchesTabsComponent }, ]; In the main-contin ...

Is Babel necessary for enabling JavaScript compatibility in my TypeScript React project, excluding Create React App?

This is the webpack configuration for my React project built in TypeScript, module.exports = { mode: 'development', entry: ['./src/main.tsx'], module: { rules: [ { // Rule for ts/tsx files only, no rule for js/js ...

Is it possible for me to tap into the component creation process within the Angular Router?

Inspiration struck me when I realized the potential of adding a directive to the component designed for this particular route. It would elevate the functionality by letting me convey crucial information in a more declarative manner. Despite learning that ...

How can one overcome CORS policies to retrieve the title of a webpage using JavaScript?

As I work on a plugin for Obsidian that expands shortened urls like bit.ly or t.co to their full-length versions in Markdown, I encounter a problem. I need to fetch the page title in order to properly create a Markdown link [title](web link). Unfortunatel ...

Issue with uploading files due to cross-domain restrictions in AngularJS and Web API

Having trouble uploading a CSV file from Angular using POST to a Web API endpoint, resulting in the following error: "XMLHttpRequest cannot load http://localhost:89/WebService/Upload. No 'Access-Control-Allow-Origin' header is present on the ...

Encountering an issue while attempting to initiate a nested array: "Cannot assign a value to an optional property access in the left-hand side of an assignment expression."

I am dealing with an object that contains nested arrays, structured like this: export class OrdenCompra { public id?: number, public insumos?: OrdenCompraInsumo[], } export class OrdenCompraInsumo { id?: number; traslados?: IImpuestoTraslado[]; } export ...

Iterating through typescript enums in Vue using v-for

Why is the v-for loop over an enum displaying both names and values? Is there a way to iterate only over the keys? export enum Colors { "RED" = 1, "BLUE" = 2, "GREEN" = 3, } <template> <div> <v ...

I am experiencing difficulties with integrating the Stripe checkout API into my MEAN stack development

view error image here I encountered this issue in the developer tools. check terminal error image here This is the error shown in the backend terminal. explore Stripe documentation for guidance Here are the helpful Stripe docs that guided me through. ...

Tips for conducting tests on an Observable<boolean>

I am facing an issue with handling an Observable in my code. Here is a snippet of the relevant parts: app.component.ts import { Observable } from "rxjs"; export class ProductComponent implements OnInit { ProductListLength: Num ...

``If you're looking to integrate a 360-degree product viewer into your Angular application, here is a

I am in need of showcasing a 360 Product viewer consisting of an array of 36 car images in base64 format. Despite attempting to utilize the angular-three-sixty Package by @mediaman, I was only met with an empty canvas. Does anyone have experience in implem ...

Utilizing PropTypes in React with TypeScript

I've encountered issues while trying to integrate PropTypes with Typescript: Previously, without typescript, I had successfully used: class TodoFilterItem extends Component { constructor (props) { super(props); Followed by: TodoFilterItem.prop ...

Sending a POST request in Node.js and Express may result in the request body being empty or undefined

Here is a snippet of my Typescript code: import express = require('express'); const app: express.Application = express(); const port: number = 3000; app.listen(port, () => { console.log("The server is now running on port" + port); ...

Encountering a Npm ERR! when deploying Angular 6 to Heroku due to missing Start script

I am experiencing an issue with my simple angular 6 app after deploying it to Heroku. When I check the logs using the command heroku logs, I encounter the following error: 2018-07-15T00:45:51.000000+00:00 app[api]: Build succeeded 2018-07-15T00:45:53.9012 ...

Is it normal that aws-eventbridge-lambda does not generate a Lambda function?

I've been experimenting with the AWS CDK (Typescript) to enhance my knowledge. I'm interested in setting up a lambda function to run daily at a specific time or at intervals of N minutes. Since I anticipate having multiple functions, it would be ...

Tips for utilizing generated *.d.ts files

I have been utilizing a Visual Studio 2017 extension called TypeScript Definition Generator to automatically create TypeScript interfaces for my MVC-ViewModels. Despite trying various similar tools, they all seem to result in the same output (*.cs.d.ts-Fil ...

Could it be that the Angular query is not returning any data? Or perhaps the issue lies with the dropdown selection not retrieving the data. It's possible that there may be a

I am facing an issue where I am not receiving the complete data from my form query. The query includes a search and mat select dropdown. I need both the selected values back in order to filter elements based on them. However, I am only getting the 'ti ...

Can you guide me on how to programmatically set an option in an Angular 5 Material Select dropdown (mat-select) using typescript code?

I am currently working on implementing an Angular 5 Material Data Table with two filter options. One filter is a text input, while the other is a dropdown selection to filter based on a specific field value. The dropdown is implemented using a "mat-select" ...

Incorporate typings into your CDN integration

I'm interested in utilizing a CDN to access a JSON validation library, as it's expected to provide faster performance (due to retrieving the file from the nearest server within the CDN). The JSON validation library in question can be found here: ...

The Fusion of Apollo GraphQL Server and TypeScript: A Match Made

Lately, I've been immersed in a project that utilizes the node.js + express + typescript + Apollo server stack. During my research on Apollo client, I came across the TypeScript section, but surprisingly found little information regarding TypeScript f ...

Personalized Carousel using Ng-Bootstrap, showcasing image and description data fields

I have been working on customizing an Angular Bootstrap Carousel and have managed to successfully change the layout. I now have two columns - with the image on the right and text along with custom arrows on the left. My goal is twofold: First, I am lookin ...