Steps to retrieve a date from a form control

html

<form [formGroup]="searchForm" (ngSubmit)="search()">
  <div class="row">
    <div class="col">
      <input type="date" class="form-control" formControlName="startDate" >
    </div>
    <div class="col">
      <input type="date" class="form-control" formControlName="endDate" >
    </div>
    <div class="col">
      <button type="submit" class="btn btn-primary">Submit</button>
    </div>
  </div>
</form>

ts.

  searchForm = new FormGroup({
      startDate: new FormControl(),
      endDate: new FormControl(),
    }
  );

i need the date in this format: '2022-12-31'

but when I display it using console.log(this.searchForm.value.startDate), the output is simply:

Output : 2022-12-31

I attempted to fix this by converting startDate to a Date object like this:
startDate = new Date(this.searchForm.value.startDate)
however, the Output remained as: 1970-01-01T00:00:00

Answer №1

When dealing with an input type date that returns a string (and is fed by a string), two functions can be utilized.

formatDate(date: Date | null): string | null {
  if (date)
     return date.getFullYear()+'-'+
            ('00'+(date.getMonth()+1)).slice(-2)+'-'+
            ('00'+date.getDate()).slice(-2)
  return null
}
parseDate(value: string | null): Date | null {
  if (value)
     return new Date(value)
  return null;
}

Instead of using formControl, ngModel and ngModelChange can be used as alternatives.

<form [formGroup]="searchForm" (ngSubmit)="search()">
      <input type="date" class="form-control" 
          [ngModel]="formatDate(searchForm.get('startDate').value)"
          (ngModelChange)="searchForm.get('startDate').setValue(parseDate($event))"
         [ngModelOptions]="{standalone:true}"
 >
 ...
</form>

View the example on StackBlitz

Answer №2

Obtain a YYYY-MM-DD formatted string or an empty string from the user input of type date field. Refer to <input type="date">

If the input is left blank, it will default to January 1, 1970, 00:00:00 UTC (the ECMAScript epoch). Check out the Date() constructor for more information.

const dateEmpty = new Date(“”);
const dateFromString = new Date(“2022-12-31”);
   
console.log(dateEmpty);
console.log(dateFromString);

The method of handling cases where the user leaves the date field empty is at your discretion. For instance, you could enforce input using validation with Validators.required and prevent form submission until a date is entered. Alternatively, you could assign a TypeScript type Date | null where null indicates that no date was provided.

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 troubleshoot issues in Visual Studio when using Angular, Firebase, and Chrome that result in a "Browser or

I'm currently using Visual Studio for debugging an Angular application that requires authentication through Firebase. I have successfully installed the "Debugger for Chrome" and everything is running smoothly until I need to log in, which authenticate ...

Get rid of the Modal simply by clicking on the X mark

Objective: The modal should only be closed by clicking the X mark and not by clicking outside of it. Challenge: I am unsure how to resolve this issue when using the syntax code [config]="{backdrop: 'static'}" Additional Information: I am new ...

Why does the property of {{hero.name}} function properly in a <h> tag but not in an <img> tag?

Within this template, the code below functions correctly: <h3>{{hero.name}}</h3> It also works for: <a routerLink="/details/{{hero.id}}">{{hero.name}}</a> However, there seems to be an issue with the following image path ...

Assign a property to an array of objects depending on the presence of a value in a separate array

Looking to manipulate arrays? Here's a task for you: const arrayToCheck = ['a', 'b', 'c', 'd']; We have the main array as follows: const mainArray = [ {name:'alex', code: 'c'}, ...

Why did my compilation process fail to include the style files despite compiling all other files successfully?

As English is not my first language, I kindly ask for your understanding with any typing mistakes. I have created a workspace with the image depicted here; Afterwards, I executed "tsc -p ." to compile my files; You can view the generated files here Unf ...

In Angular/Typescript, dynamically add a class to a `td` element when it is clicked. Toggle the class on and off

My problem arises when trying to individually control the arrow icons for each column in my COVID-19 data table. By using Angular methods, I aim to show ascending and descending arrows upon sorting but run into the challenge of changing arrows across all c ...

Setting up a passthrough for a directory of external resources in Angular

Issue: I am currently facing a challenge with a project that requires accessing photos from a system that has recently been updated from AngularJs to Angular 16. Initially, we were able to serve these photos from a virtual directory like https://myawesom ...

The issue arises when attempting to call a method from the same service within jsPDF in an Angular environment

Below you will find my Angular project's pdfService. I am facing an issue where calling the this.formatter() method inside myPDF is not functioning properly. export class pdfService { formatter(value: number): string { return new Intl.N ...

What is the best way to retrieve the previous URL in Angular after the current URL has been refreshed or changed

Imagine being on the current URL of http://localhost:4200/#/transactions/overview/5?tab=2 and then navigating to http://localhost:4200/#/deals/detail/ If I refresh the deals/detail page, I want to return to the previous URL which could be something like h ...

Steps for constructing an object literal with a property designated as the `keyof` type

Struggling to articulate my question, here is a simplified code snippet outlining what I aim to accomplish. class Example<T, TId extends keyof T> { public create(id: T[TId]): T { return { [TId]: id, // Encounter an error at this point. Ob ...

The never-ending cycle of an Angular dropdown linked to a function being repeatedly invoked

I am currently working with a PrimeNg dropdown that is fetching its options through a function call. However, I have noticed that this function is being called an excessive number of times. Could this potentially impact the performance or any other aspect? ...

The execution time of Node's Promises.all() function is unreasonably slow

I need to add a table containing data on sent emails after each email has been successfully sent. Within a loop, I am populating an array to be resolved using the Promise.all(). insertData is a function that adds data, requiring two parameters: connector, ...

Angular: Observing changes in the store and sending a message from a Service component to another component once the Service has finished specific tasks

Within our codebase, we introduce two classes known as GetDataAsyncService. This service is designed to wait for a change in the store before executing the block of code contained within it. By utilizing observables and subscribing to data changes with t ...

The MemoizedSelector cannot be assigned to a parameter of type 'string'

Currently, my setup involves Angular 6 and NgRX 6. The reducer implementation I have resembles the following - export interface IFlexBenefitTemplateState { original: IFlexBenefitTemplate; changes: IFlexBenefitTemplate; count: number; loading: boo ...

What is the best way to extract the ng-reflect-value and compare it with the expected value in testing?

After reviewing the attachment, I am utilizing the following code snippet "private readonly By _idTxt = By.XPath(".//*[@class='metric-set-details-dropdown']/../button[ng-reflect-value]");" in an attempt to extract the value of the attribute ng-re ...

Is there a way for me to deduce types dynamically?

Is there a way to dynamically infer types, similar to a union type? I am trying to register multiple elements from different parts of the code using a method like registerElement(...), but I am struggling with inferring these new types in TypeScript. This ...

What is the process for retrieving paginated data from the store or fetching new data from an API service within an Angular 2 application using ngrx-effects?

After coming across this insightful question and answer about the structure of paginated data in a redux store, I found myself pondering how to implement similar principles using ngrx/store in an angular 2 application. { entities: { users: { 1 ...

The useState variable's set method fails to properly update the state variable

I am currently developing an application with a chat feature. Whenever a new chat comes in from a user, the store updates an array containing all the chats. This array is then passed down to a child component as a prop. The child component runs a useEffect ...

Global installation of Node modules

How do I reference globally installed node modules? For example, if I have a package.json file and I choose to install all the node modules listed in it globally (located at C:\Users\MyaccountName\AppData\Roaming\npm), how can I ac ...

Running an Angular 4/2 application on IIS server

As I attempt to deploy my Angular 4 application on IIS 10, a peculiar issue arises. Everything seems to work seamlessly when navigating from one route to another by clicking links within the application. However, if I type in the same link directly into th ...