"Implementing an Angular material date range picker that requires both the start and end dates to be selected in conjunction with a form control

I am working with a Mat date range picker where the start date and end date are form controls in the ts code for the component.

To retrieve the values of the date picker, I am using the combineLatest method on the start and end date.

The issue I am facing is that when I initially select a start date/end date, the code executes correctly. However, if I go back and modify either date, the combineLatest function is triggered immediately when I click on a start date because the end date already has a value.

How can I make the code wait for both the start date and end date to change before executing?

Parent ts code -

dateRangeStart: FormControl = new FormControl();
dateRangeEnd: FormControl = new FormControl();
...
...
...
combineLatest([
  this.dateRangeStart.valueChanges, 
  this.dateRangeEnd.valueChanges
]).subscribe((dates) => {
    //logic
  }
})

Parent HTML

      <app-date-picker 
        [dateRangeStart]="dateRangeStart"
        [dateRangeEnd]="dateRangeEnd">
      </app-date-picker>

DatePicker TS

  @Input() dateRangeStart!: FormControl;
  @Input() dateRangeEnd!: FormControl;
  maxDate: Date | undefined = undefined;

  constructor() { }

  ngOnInit(): void {
    this.dateRangeStart.valueChanges.subscribe(dateRangeStart => {
      if (!!dateRangeStart) {
        const maxDate = new Date(dateRangeStart);
        maxDate.setDate(maxDate.getDate() + 7);
        this.maxDate = maxDate;
      } else {
        this.maxDate = undefined;
      }
    })
  }

DatePicker HTML

<div>
  <mat-form-field appearance="fill">
    <mat-label>Enter a date range</mat-label>
    <mat-date-range-input 
      [rangePicker]="picker"
      [max]="maxDate">
      <input 
        matStartDate 
        [formControl]="dateRangeStart" 
        placeholder="Start date">
      <input 
        matEndDate 
        [formControl]="dateRangeEnd" 
        placeholder="End date">
    </mat-date-range-input>
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-date-range-picker #picker></mat-date-range-picker>
  </mat-form-field>
</div>

Answer №1

It seems that resetting the datepicker ts component when you "go back" triggers combineLatest to immediately execute with the last valid values from the observables. Some possible solutions include:

  1. Ensure you flush
    this.dateRangeStart.valueChanges, this.dateRangeEnd.valueChanges
    in the datepicker ts component using the ngOnDestroy lifecycle hook.
  2. Consider moving the combineLatest function inside the datepicker ts component and have the parent component subscribe to it.

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: Unresolved Template Issue - MatDivider

Encountering the following issue: Uncaught Error: Template parse errors: More than one component matched on this element. Ensure that only one component's selector can match a given element. Conflicting components: MatDivider,MatDivider (" {{head ...

The size of the content in a JWT Bearer token may be restricted by certain external fire

We are encountering an issue related to the size of JWT tokens in our system. Our current setup includes an Angular front-end and an authentication service utilizing IdentityServer4. After successful authentication, the next step involves retrieving the u ...

The Function-supported Operation is having trouble implementing a modification related to Geohash/Geopoint - the Object Type requires a String format

Summary: My function-based Action that tries to set a GeoPoint as a Geohash property is failing with an error suggesting it was anticipating a string. I have an Object Type with a String property that has been designated as a Geohash in the property edito ...

Having trouble with validation messages not displaying correctly in Angular after removing a value. What is the correct approach to fix this issue

I've encountered an issue with Angular validation where it's triggering validation on page load, which is not desired. Additionally, when I enter a value, the validation message disappears, but if I return to the textbox and delete the input, the ...

macangular 2 template for developing with servicestack

Is there a method to create a project on a Mac using Rider or VS Code without the need for Visual Studio? I prefer not to install Windows just to create an empty project to test out a potentially useful template. ...

The tsconfig.json file is located separate from the project directory

Working on my project called "portal" has been quite an interesting journey. As I delved deeper into development, I realized the need for multiple projects within the repository. This led me to restructure my project setup like this: https://i.sstatic.net ...

The parameter type (key: string, id: string, pagination: number) in the argument does not match the expected type of Boolean for the parameter

I'm facing an issue while trying to implement the following documentation: https://swr.vercel.app/ using my own setup: import React, { useEffect } from 'react' import PatientsTable from 'components/patients/PatientsTable' import ...

Display a popup notification when clicking in Angular 2

Can anyone help me with displaying a popup message when I click on the select button that says "you have selected this event"? I am using Angular 2. <button type="button" class="button event-buttons" [disabled]="!owned" style=""(click)="eventSet()"&g ...

What is the reason behind capitalizing Angular CLI class file imports?

After creating a basic class in Angular using the CLI starter, I encountered an issue when trying to use the imported class. Instead of functioning as expected, it returned an empty object. Through troubleshooting, I discovered that simply changing the fil ...

(TS 2556) I'm puzzled as to why a type error is being thrown for a spread argument that was clearly defined and passed as a rest parameter

function debouncePromise<TParams extends Array<unknown>, TRes>( fn: (a: TParams) => Promise<TRes>, time: number, ) { let timerId: ReturnType<typeof setTimeout> | undefined = undefined; return function debounced(...args: TP ...

Retrieve functions contained within the component.ts file of an Angular library: tips and tricks

I have developed an Angular library, named 'mylib', where I have utilized only the mylib.component.ts file. The HTML element codes are included inside the template variable of this file, along with the functions responsible for modifying these el ...

The project needs to either compile a comprehensive list of all files or adhere to an 'include' pattern

When working in VSCode, I came across this warning: https://i.sstatic.net/jvUsk.png The line of code that triggered the TypeScript warning is: import packageJson from "../package.json"; Interestingly, the project builds and lints without any issues: $ ...

Angular's use of observable async within an if statement allows for dynamic

After attempting the following code, I found that it was not functioning properly this.users$ = this.userService.get(); <span *ngIf="!users$ | async">No data</span> ...

Starting a nested JSON structure with TypeScript and Angular 7

I'm encountering an error when attempting to make a POST request by sending an object TypeError: Can not set property 'ItemCode' of undefined My setup involves Angular 7 and Typescript Here is my initial JSON: objEnvio:any = <an ...

2 entities - perform an action once both have successfully provided data

Upon calling this.pokojeService.pobierzPokoje() and this.pokojeService.pobierzTypyPokoi(), I subscribe to their respective observables. Once the data is retrieved, it is stored in this.pokoje and this.pokojeTypy variables. These two observables are crucia ...

The specified type 'x' cannot be assigned to the type 'x'. Error code: 2322

I encountered an issue with the code in @/components/ui/billboard.tsx file import { Billboard } from "@/types" interface BillboardProps { data: Billboard; }; const BillboardComponent: React.FC<BillboardProps> = ({ data }) => ...

Tips for updating routerlink in navigation bar in Angular 4

I'm encountering an issue with routing to the wrong routelink. How can I prevent this from happening? My apologies for my lack of experience. The error message displayed in the Chrome console is: ERROR Error: Uncaught (in promise): Error: Cannot mat ...

I am having trouble accessing my JSON data via HTTP get request in Angular 2 when using TypeScript

I am working on developing a JSON file configuration that can be accessed via HTTP GET request in order to retrieve the desired value from the config file and pass it to another component. However, whenever I try to return the value, it shows up as undefin ...

Handle errors originating from unsuccessful connections to a server named "Event" when using RxJS's fromEvent method

Using rxjs fromEvent to establish a connection with a named sse Event, I am looking to handle an Error in case of connection loss namedEvent() { try { const eventSource = new EventSource( 'adress' ); return fromEvent ...

Is it necessary to ensure application readiness before proceeding with unit testing exports?

I've been facing a challenge while trying to utilize Jest for unit testing an express API that I've developed. The issue arises when the database needs to be ready before running the test, which doesn't seem to happen seamlessly. In my serve ...