Programmatically populating the date picker in angular material

I have implemented the Angular Material date picker in one of the components of my Angular project. This specific component consists of two tabs, and I am using *ngIf to display only one tab at a time based on user interaction. When a user selects a date in one tab and then navigates away to another tab within the same component, I want to ensure that the selected date is retained when they return.

This is how I am handling it in the HTML side:

<mat-form-field class="dropdownWidth">
      <input #dateInput matInput [matDatepickerFilter]="myFilter" [matDatepicker]="picker"
             placeholder="Choose a date"
             [value]="datePickerDate"
             [(ngModel)]="datePickerDate"
             (dateChange)="addDateEvent($event)"
             [disabled]="selectedOperator.length === 0 && userDateRange.length === 0">
      <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
      <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

And in the TS file:

addDateEvent(event) {
   this.datePickerEvent = event;
   this.datePickerDate = new Date(`${event.value['_i'].month + 1}-${event.value['_i'].date}-${event.value['_i'].year}`);
   this.formatDate = moment(event.value).format('YYYY-MM-DD');
}

However, I am facing an issue where the date value is not being retained when navigating back. Any insights on how I can achieve this?

Feel free to check out the sample on StackBlitz.

Answer №1

The reason it's not functioning is due to the absence of a stored value. To resolve this, you need to create a TypeScript variable:

selectedDate: any;

In your HTML file:

<p> Selected Date:  {{ selectedDate | date }} </p>

<mat-form-field>
    <input matInput [(ngModel)]="selectedDate" 
        [matDatepicker]="datepicker" placeholder="Pick a date">
    <mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
    <mat-datepicker #datepicker></mat-datepicker>
</mat-form-field>

You can review the full code on StackBlitz

Answer №2

Your approach does not include any bindings in the example provided. Consider using [(ngModel)] to properly capture and retain the selected value.

To achieve this, implement the following code:

<mat-form-field>
          <input matInput [(ngModel)]="date" [matDatepicker]="picker" placeholder="Choose a date">
          <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
          <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

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

Two separate tables displaying unique AJAX JSON response datasets

As a beginner in javascript, I am facing a challenge. I want to fetch JSON responses from 2 separate AJAX requests and create 2 different tables. Currently, I have successfully achieved this for one JSON response and table. In my HTML, I have the followi ...

Combining two Unix timestamps into a single value

Looking for a way to condense a date range into GET parameters for my application, I pondered the possibility of encoding two Unix timestamps into a single parameter to minimize URL length. While a basic CSV of two timestamps would suffice, my aim is to f ...

Angular Express - PDF Serving

I'm currently developing an application using the MEAN stack and I'm facing an issue with displaying a PDF file from the backend (Express) to the frontend (Angular). Each time I try to transmit the file, it ends up getting corrupted. Does anyone ...

Adding a <div> within a <form> on button click using HTML and jQuery tactics

Whenever the '+' button [the addMore() function] is clicked, I want to insert the following div structure. Although I am able to add the div structure, the alignment of the input text is not equal as compared to the hard coded version. Here is t ...

Issues encountered when using .delay() in conjunction with slideUp()

Issue: The box is not delaying before sliding back up on mouse out. Description: Currently, when hovering over a div with the class ".boxset" called "#box", another div "#slidebox" appears. Upon moving the mouse away from these two divs, #slidebox slides ...

Selecting a database design pattern for varying database types

After creating a class to manage interactions with my database, I realized that I need separate classes for two different modes: admin and client. class MyDatabase { connect() { /* ... */ } } So, I decided to create two new classes: class MyDatabaseAd ...

Automatically adjust Kendo Grid column widths, with the option to exclude a specific column from

Seeking a solution to dynamically adjust column widths in a Kendo Grid using column(index = n) or column(headingText = 'Address'). For automatically fitting column widths, the following approach can be used: <div id="example ...

Leverage variables in JavaScript to establish a unique style

function AdjustScale(){ scaleX = window.innerWidth / 1024; scaleY = window.innerHeight / 768; element = document.getElementById("IFM"); element.style.transform = "scale(" + scaleX + ", " + scaleY + ")"; } I'm facing an issue with thi ...

Obtain the parameters of a function within another function that includes a dynamic generic

I am attempting to extract a specific parameter from the second parameter of a function, which is an object. From this object, I want to access the "onSuccess" function (which is optional but needed when requested), and then retrieve the first dynamic para ...

Turning On and Off Hover Effects in AngularJS

I am looking to implement a feature that enables and disables the hover state on an element based on certain conditions. As a newcomer to Angular, I am unsure of how to approach this and haven't been able to find a solution online. Here is a sample o ...

Tips for creating parameterized keys for a specific type in Typescript

I've encountered a challenge while transitioning my react-native project from Flow to TypeScript. The stumbling block is recreating this specific type from Flow: declare type ApolloData<T, nodeName: string = 'node'> = { [nodeName]: ...

Observing rxjs Observable - loop through the results and exit when a certain condition is met / encountering an issue with reading property 'subscribe' of an undefined value

I'm fairly new to working with rxjs and I've been struggling to find the right operator for what I want to achieve. Here's my scenario - I have an array that needs to be populated with results from another observable. Once this array has en ...

Add CSS properties to child elements that are not of a specific selector, while styling their descendants without any restrictions

Seeking assistance for an Angular application, but the query also pertains to CSS principles in general. In my Angular project, I have a main component containing several child components, all with standard view encapsulation. Specifically, I am looking t ...

Is there a way to program a function that can automatically trigger or refresh an HTTP POST method?

How can I create a method in a distant component that will run a POST request when a button is clicked? I believe I need to use a service in this situation. It's not necessary for it(this.qwe) to be in the constructor, it's just an example... ...

JavaScript-powered dynamic dropdown form

I need help creating a dynamic drop-down form using JavaScript. The idea is to allow users to select the type of question they want to ask and then provide the necessary information based on their selection. For example, if they choose "Multiple Choice", t ...

Having trouble updating the sequelize-cli configuration to a dynamic configuration

Encountering an issue while attempting to switch the sequelize-cli configuration to dynamic configuration, following the instructions in the documentation. I have created the .sequelizerc-file in the project's root directory and set up the path to con ...

The error message encountered is "Uncaught (in promise) Error: Unable to access attributes of an undefined object (reading 'launch')."

I am currently learning electron.js by developing a basic application that extracts information from a website. However, I am encountering a frustrating and annoying error. Here is the folder structure of my project The following code snippet represents ...

To ensure that checkboxes are automatically checked in AngularJS 1.5, the model should be bound to the objects without using the ng-checked

Due to various conflicts and dependencies, I have opted to use AngularJS 1.5.x instead of 1.6.x, which has led me to encounter some issues with ng-checked functionality. Within my ng-repeat loop, I am dealing with 2 objects: vm.stateList, containing all ...

Retrieving information from MongoDB to populate the Redux store

Currently, I have successfully set up my Node API and MongoDB. My next focus is on integrating Redux into my application. Below are some code snippets that I would like to share: The Server Order controller is functioning as expected : const getTotal = as ...

The issue with Google Maps API not loading is being caused by a problem with the function window.handleApiReady not being

Having trouble with the Google Maps API, specifically encountering an error during page load that says window.handleApiReady is not a function, even though it definitely exists. Examining the code snippet below reveals its usage as a callback function: ...