components icon indicating copy to clipboard operation
components copied to clipboard

datepicker: (change) event does not work in mdInput

Open da45 opened this issue 9 years ago • 32 comments

Bug

change event does not work

<md-input-container>
    <input mdInput [mdDatepicker]="picker" (change)="doSomething($event)">
     <button mdSuffix [mdDatepickerToggle]="picker"></button>
</md-input-container>

<md-datepicker #picker></md-datepicker>    

What is the expected behavior?

change event must work

What is the current behavior?

when choose a date from datepicker no (change) event is triggered

Which versions of Angular, Material, OS, TypeScript, browsers are affected?

Angular 4.1.2 & material 2.0.0-beta.5

da45 avatar May 17 '17 09:05 da45

In reactive form, we can change or update already selected datepicker value by setValue() by click event. For example, this.myForm.controls['selectedDate'].setValue("07/08/2017");

sahil-developer-88 avatar Jul 06 '17 13:07 sahil-developer-88

Using (blur) instead of (change) will result in the function only being called if the input is changed using 2.0.0-beta.8 and seems like a simple workaround.

rbj325 avatar Jul 09 '17 01:07 rbj325

Hi all, What if I need to use rxjs/Observable? Is there any workwround? I was hoping to subscribe the changes, since it can be changed by typing or the button. Any suggestion is appreciated.

    <md-input-container>
      <input mdInput #businessDatePickerInput [mdDatepicker]="businessDatePicker" placeholder="business date">
      <button mdSuffix [mdDatepickerToggle]="businessDatePicker"></button>
    </md-input-container>
    <md-datepicker #businessDatePicker></md-datepicker>
    Observable.fromEvent(this.businessDatePickerInput.nativeElement, 'change')
      .subscribe(() => {
        console.log('on change');
      });

kylelix7 avatar Jul 26 '17 21:07 kylelix7

@kylelix7 did you found any solution? I also need to use an observable and 'selectedCanged' does not get triggered. and 'change' only works if the input is changed after typing

alexandrupaul7 avatar Aug 03 '17 07:08 alexandrupaul7

@kylelix7 @alexandrupaul7

With the master build, you can do something like this. It will respond to input changes and datepicker selections.

Observable
  .merge(this.datepickerInput.dateChange, this.datepickerInput.dateInput)
  .map(e => e.value)
  .distinctUntilChanged((a, b) => a.toString() === b.toString())
  .subscribe(date => console.log(date));

http://plnkr.co/edit/YFwWl6sK7VxdUgsEiDM5?p=preview

willshowell avatar Aug 03 '17 12:08 willshowell

Actually, there's a workaround to get thru this, and I faced a similar situation while I was working on start/end dates using reactive forms - where I had to validate them both at the same time using the input from picker button and text box.

Below is the code, both the html and ts source of SomeComponent

some.component.html

<form [formGroup]="someFormGroup">
  <md-input-container class="input-container">
    <input #startAtUtc mdInput type="date" formControlName="startAtUtc" placeholder="Start date" [mdDatepicker]="startAtUtcPicker" [mdDatepickerFilter]="filterStartAtUtc">
    <button mdSuffix [mdDatepickerToggle]="startAtUtcPicker"></button>
  </md-input-container>
  <md-datepicker #startAtUtcPicker (selectedChanged)="onStartAtUtcChange($event)"></md-datepicker>
  <md-input-container class="input-container">
    <input #endAtUtc mdInput type="date" formControlName="endAtUtc" placeholder="End date" [mdDatepicker]="endAtUtcPicker" [mdDatepickerFilter]="filterEndAtUtc">
    <button mdSuffix [mdDatepickerToggle]="endAtUtcPicker"></button>
  </md-input-container>
  <md-datepicker #endAtUtcPicker (selectedChanged)="onEndAtUtcChange($event)"></md-datepicker>
</form>

some.component.ts

...
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/add/observable/fromEvent';
...
export class SomeComponent implements OnDestroy, OnInit {
  @ViewChild('startAtUtc') startAtUtcRef: ElementRef;
  @ViewChild('endAtUtc') endAtUtcRef: ElementRef;

  someFormGroup: FormGroup;

  private startAtUtc$: Subscription;
  private endAtUtc$: Subscription;

  filterStartAtUtc = (startAtUtc: Date, endAtUtc?: Date) => {
    // NOTE: implement logic
    return true;
  };

  filterEndAtUtc = (endAtUtc: Date, startAtUtc?: Date) => {
    // NOTE: implement logic
    return true;
  }

startDateValidator = (): AsyncValidatorFn => {
    return (control: AbstractControl): Promise<{ errors: ValidationErrors }> => {
      return new Promise(resolve => {
        // NOTE: implement validation rule(s)
        resolve(undefined);
      });
    };
  };

  endDateValidator = (): AsyncValidatorFn => {
    return (control: AbstractControl): Promise<{ errors: ValidationErrors }> => {
      return new Promise(resolve => {
        // NOTE: implement validation rule(s)
        resolve(undefined);
      });
    };
  };

  constructor(private readonly formBuilder: FormBuilder) {
  }

  ngOnInit(): void {
    this.someFormGroup = this.formBuilder.group({
      startAtUtc: ['', undefined), Validators.required, [this.startDateValidator()]],
      endAtUtc: ['', Validators.required, [this.endDateValidator()]]
    });

    this.startAtUtc$ = Observable.fromEvent(this.startAtUtcRef.nativeElement, 'change')
      .subscribe(() => this.someFromGroup.get('endAtUtc').updateValueAndValidity());

    this.endAtUtc$ = Observable.fromEvent(this.endAtUtcRef.nativeElement, 'change')
      .subscribe(() => this.someFromGroup.get('startAtUtc').updateValueAndValidity());
  }

  ngOnDestroy(): void {
    this.startAtUtc$.unsubscribe();
    this.endAtUtc$.unsubscribe();
  }

  onStartAtUtcChange($event: any): void {
    if ($event instanceof Date && !isNaN($event.valueOf())) {
      this.someFromGroup.get('startAtUtc').setValue($event);
      this.someFromGroup.get('startAtUtc').markAsTouched();

      this.someFromGroup.get('endAtUtc').updateValueAndValidity();
    }
  }

  onEndAtUtcChange($event: Date): void {
    if ($event instanceof Date && !isNaN($event.valueOf())) {
      this.someFromGroup.get('endAtUtc').setValue($event);
      this.someFromGroup.get('endAtUtc').markAsTouched();

      this.someFromGroup.get('startAtUtc').updateValueAndValidity();
    }
  }
}

fulls1z3 avatar Aug 24 '17 10:08 fulls1z3

selectedChanged will work for a mouse click in the datepicker. to get the change from the text-field you can do as @willshowell showed in this comment above: https://github.com/angular/material2/issues/4615#issuecomment-303460818

The docs as of beta-10 say: https://material.angular.io/components/datepicker/overview#input-and-change-events

image

To get both the mouse click and the text field changes via the docs suggested implementation, see @willshowell's plunkr above: https://github.com/angular/material2/issues/4615#issuecomment-319952531

At first I tried this example based on the docs, but it didn't work: https://github.com/angular/material2/blob/master/src/demo-app/datepicker/datepicker-demo.ts

@willshowell thanks!

tyler2cr avatar Sep 11 '17 18:09 tyler2cr

This worked for me. Although not super pretty.

.html `

                    <input mdInput [mdDatepicker]="minDatePicker" (change)="onManualMinDateChange($event)"
                        placeholder="Min date">

                    <button mdSuffix [mdDatepickerToggle]="minDatePicker"></button>

                </md-input-container>
                <md-datepicker #minDatePicker (selectedChanged)="onMinDateChange($event)"></md-datepicker>

                <md-input-container>

                    <input mdInput [mdDatepicker]="maxDatePicker" (change)="onManualMaxDateChange($event)"
                        placeholder="Max date">

                    <button mdSuffix [mdDatepickerToggle]="maxDatePicker"></button>

                </md-input-container>

                <md-datepicker #maxDatePicker (selectedChanged)="onMaxDateChange($event)"></md-datepicker>

            </p>`

.ts

` private minDate: Date; private maxDate: Date; (...) onMinDateChange(event) { console.log('min Date changed'); console.dir(event); this.minDate = event; console.log(this.minDate); }

onMaxDateChange(event) { console.log('max Date changed'); console.dir(event); this.maxDate = event; console.log(this.maxDate); }

onManualMinDateChange(event) { console.log('manual min Date changed'); const eve = event.target.value; this.minDate = new Date(eve); console.log(this.minDate); }

onManualMaxDateChange(event) { console.log('manual max Date changed'); const eve = event.target.value; this.maxDate = new Date(eve); console.log(this.maxDate); }`

shiamalon avatar Sep 20 '17 10:09 shiamalon

<mat-form-field>
   <input matInput [matDatepicker]="pickerStart" placeholder="From" (dateInput)="yourFunction($event)" (dateChange)="yourFunction($event)" disabled>
   <mat-datepicker-toggle matSuffix [for]="pickerStart"></mat-datepicker-toggle>
   <mat-datepicker disabled="false" #pickerStart></mat-datepicker>
</mat-form-field>

(dateInput) and (dateChange) works just fine

mariehelene avatar Dec 29 '17 17:12 mariehelene

Is there an event to identify when the user clicks either next/previous month? I can't find it :/

bvasquezd avatar May 06 '19 14:05 bvasquezd

@bvasqueztbc I've looked for the same event too, but I didn't find it :-(

andreatosi89 avatar May 29 '19 14:05 andreatosi89

This issue has been automatically locked due to inactivity. Please file a new issue if you are encountering a similar or related problem.

Read more about our automatic conversation locking policy.

This action has been performed automatically by a bot.