kekeh / angular-mydatepicker

Angular datepicker and date range picker :date:
https://kekeh.github.io/angular-mydatepicker/
MIT License
1 stars 11 forks source link

ExpressionChangedAfterItHasBeenCheckedError issue with Reactive Form #37

Closed fbanyai closed 4 years ago

fbanyai commented 4 years ago

Hi there,

I'm developing a reactive form in Angular 9 with angular-mydatepicker (btw the nicest one out there!) and by using the following sample (with buttons triggering the calendar) it works fine:

https://github.com/kekeh/angular-mydatepicker/blob/master/example/app/date-picker-reactive-forms/date-picker-reactive-forms.html

Now I'm trying to show the calendar when the user clicks in the field. But adding the (click)="dp.toggleCalendar()" to the reactive <input> tag it triggers the following error in Chrome debug panel:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value for 'ng-untouched': 'true'. Current value: 'false'.

I understand that this issue is somewhat related to this https://github.com/kekeh/mydatepicker/issues/557 but as angular-mydatepicker seems to be a brand new component I found it important to report as a new issue in this project.

Thank you very much!

kekeh commented 4 years ago

Hi @fbanyai

Can you try this:

<input class="form-control" placeholder="Select a date" angular-mydatepicker 
    name="reactiveFormsDate" formControlName="myDate"
   [options]="myDatePickerOptions" #dp="angular-mydatepicker" autocomplete="off" 
  (click)="toggleCalendar()"/>

define (click) like above with the given method name
import {Component, OnInit, Renderer2, ViewChild, ChangeDetectorRef} from '@angular/core';
import {IAngularMyDpOptions, IMyDateModel, AngularMyDatePickerDirective} from 'angular-mydatepicker';

@ViewChild('dp') myDp: AngularMyDatePickerDirective;

constructor(private formBuilder: FormBuilder, private cdr: ChangeDetectorRef) { }

// input click calls this method. Probably detectChanges() method call fix the problem.
toggleCalendar(): void {
  this.cdr.detectChanges();
  this.myDp.toggleCalendar();
}

You can also take a pull from the repo. I updated reactive forms example. I didn't see any error in reactive forms example after this change.

Instructions to run example app: https://github.com/kekeh/angular-mydatepicker#development-of-this-component

fbanyai commented 4 years ago

Thank you very much, @kekeh !