'How to intercept Mat Datepicker value before set to control

I have an Angular Material Datepicker in my Angular 12 app, and I want to intercept its value before it is received by its FormControl.

      <input
        matInput
        [matDatepicker]="startDatePicker"
        [min]="minDate"
        [max]="maxDate"
        formControlName="start"
      />
      <mat-datepicker-toggle matSuffix [for]="startDatePicker"> </mat-datepicker-toggle>
      <mat-datepicker #startDatePicker></mat-datepicker>

This means, when I select (or type) a date, before the date is setted in the "start" control I want to be able to ask the user something with a popup. I know I could just create an Angular validation, but I do not want to show an error, just completely ignore the change if the user does not accept the popup.

I though about using directives, but I would still need a way to intercept the value from the datepicker. Any ideas?



Solution 1:[1]

I have done something similar to intercept the change and I did it like this. I had view and model controls for that particular input and if conditions were met I would set the model. So in your case it could look something like this:

this.form.get('startDatePickerView').valueChanges.subscribe(value => {
  const dialogRef = this.dialog.open(YourModal);

  dialogRef.afterClosed().subscribe(result => {
    // update the startDatePickerModel if yes
  });
});

You could create a wrapper for this logic and reuse it

EDIT:

Basically the same thing that @meqwz said in the comment

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1