Retrieving the selected date from mat-datepicker into a FormControl

When creating a POST request to an API, I encountered an issue with the mat-datepicker field as it throws an error when inside the ngOnInit() call (since nothing is selected yet). Other fields like name, email, etc. work fine, but extracting a value from the datepicker field has been challenging. How can I include this value when submitting the form?

This was my attempt:

ngOnInit() {
  this.myForm = new FormGroup({
    date_of_birth: new FormControl(new Date().toISOString(), [
       Validators.required,
       this.backendValidation.bind(this, 'date_of_birth')
    ])
   })
  }


<mat-form-field>
  <mat-label>Date</mat-label>
  <input matInput [matDatepicker]="date_of_birth" formControlName="date_of_birth" />
  <mat-datepicker-toggle matSuffix [for]="date_of_birth"></mat-datepicker-toggle>
  <mat-datepicker #date_of_birth></mat-datepicker>
</mat-form-field>

Answer №1

When working with HTML:

<form [formGroup]="empForm" (ngSubmit)="onSubmit()">
<mat-form-field>
    Date
    <input matInput [matDatepicker]="picker" formControlName="date_of_birth" />
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</form>

<button (click)="get()">get</button>

Within the TypeScript file:

this.empForm = this.fb.group({
  date_of_birth: new FormControl(new Date(), [
    Validators.required
  ])
});

To log to the console:

get(){
 console.log(this.empForm.get('date_of_birth').value);
}

If you encounter any issues, it could be related to the custom validator you are using -

this.backendValidation.bind(this, 'date_of_birth')
.

Give this a try and see if it resolves your problem!

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

Concealing the sidebar in React with the help of Ant Design

I want to create a sidebar that can be hidden by clicking an icon in the navigation bar without using classes. Although I may be approaching this incorrectly, I prefer to keep it simple. The error message I encountered is: (property) collapsed: boolean ...

Verifying the Loading of a Module in Angular 5

I am working on Angular 5 and I am trying to figure out how to determine if a module has been loaded already so that I can avoid displaying the spinner unnecessarily. Currently, this is my code: constructor(private loaderService: LoaderService, private ro ...

Chart.js Axis Labels Orientation Guidelines

I am currently utilizing chart.js within an Angular 8 environment using Primeng. I am looking to customize the options for my chart as follows: For the y-axis ticks, set textDirection to 'ltr' For the x-axis ticks, set textDirection to 'rtl ...

How can I set a document ID as a variable in Firebase Firestore?

I recently set up a firestore collection and successfully added data (documents) to it. Firestore conveniently generates unique document ids for each entry. Inserting Data this.afs.collection('questions').add({ 'question': message, &a ...

TypeScript properties for styled input component

As I venture into TS, I’ve been tasked with transitioning an existing JS code base to TS. One of the challenges I encountered involves a styled component in a file named style.js. import styled from "styled-components"; export const Container ...

Using BeautifulSoup to extract data from a webpage containing JavaScript

Hello everyone! I am reaching out for help once more. While I am comfortable scraping simple websites with tags, I recently came across a more complex website that includes JavaScript. Specifically, I am looking to extract all the estimates located at the ...

Error occurred while executing 'npm start' command in ReactJS due to the module 'babel-code-frame' being unable to be located

Every time I attempt to run 'npm start' in the frontend of my application, the terminal spits out a massive error. My package.json file doesn't show any script errors, and I've deleted the 'node_modules' folder and reinstalle ...

End node.js once and for all

After starting my server using forever start start.js It ran normally. However, when I attempted to stop it with forever stopall The server was removed from forever list as expected Nevertheless, upon running lsof -i tcp:3000, my server still showed u ...

Is it possible to arrange a react map based on the length of strings?

I am working on a React function that loops through an object and creates buttons with text strings retrieved from the map. I want to display the text strings in order of their length. Below is the code snippet for the function that generates the buttons: ...

Ensuring the correctness of phone numbers by validating them with country codes through the use of

I'm currently working on validating phone numbers using intl-tel-input, following the example provided at Below is the code snippet I've been using: var telInput = $("#phone"), errorMsg = $("#error-msg"), validMsg = $("#valid-msg"); // initial ...

Guide on storing images in a designated folder using CodeIgniter

My code is located in view/admin_view2.php <?php echo form_open_multipart('home_admin/createBerita'); ?> <div class="form-group" > <label class="control-label">upload foto</label> <inpu ...

Prevent draggable function in jQuery-UI for specific elements

I'm in the process of creating a website that mimics a desktop interface, and I want to be able to easily move around the windows. To achieve this functionality, I am incorporating jQuery-UI along with the .draggable() method. My current HTML structur ...

Tips for including items in a list nested within a dictionary using JavaScript

I'm currently working with a JavaScript dictionary and I need to insert an element into a list that belongs to a specific key within the dictionary. Check out the code snippet below: lines = [ [1,2], [2,4], [2,3], [3,5] ]; nodes = [ ...

When the result of Ajax is identical to that obtained without Ajax, the innerHTML remains the same

I understand that utilizing innerhtml is generally considered a poor practice due to the potential for XSS vulnerabilities (). However, consider the scenario below: I have a webpage generated through a Twig template called index.html.twig. When using te ...

A step-by-step guide to incorporating expandable and collapsible images within a div element using X

I have successfully created dynamic divs with some data that expand and collapse perfectly. Now I am looking to add expand and collapse images on these divs. I am relatively new to designing in xslt. <xsl:template match="category[key!='org.model.C ...

How can we retrieve an API response using Fetch, manipulate it with JSON.stringify(), and what are the next steps in

After countless attempts, I still can't figure out what's missing here. I'm utilizing fetch to retrieve data from Mapbox: var response = fetch(myURL) .then(response => response.json()) .then(data => console.log(JSON.stringify(data))) ...

Display content exclusively within a modal specifically designed for mobile devices

I want to implement a feature where a button triggers a modal displaying content, but only on mobile devices. On desktop, the same content should be displayed in a div without the need for a button or modal. For instance: <div class="container&quo ...

What is the best way to determine the type of `rootReducer`?

My project is set up with a combination of React, Redux, Immutable.js, and TypeScript. As I worked on implementing it, I made an effort to declare types wherever possible which led me to discover an interesting issue. A code example illustrating the proble ...

Utilizing a switch statement in Jquery to target specific input elements for focus

My Objective As a user presses enter, I want to target specific input elements with a data-index attribute value between 0-2 and of type text. Then, I plan to check their attribute values using a switch statement to perform certain actions. Presented bel ...

Textbox value disappears after being updated

When I click on the edit link (name), the value from the database is displayed as a textbox. However, when I update another normal textbox (age), the value in the edit link textbox disappears. Strangely, if I input a new value into the edit link textbox, i ...