0

I'm trying to set the current date as selected in NgbDatepicker using the following code. (I'm using reactive form.)

ngOnInit() {
  this.createEmployeeLunchEntryForm();
}

createEmployeeLunchEntryForm() {
  const currentDate = new Date();
  const currentDateObj = {
    year: currentDate.getFullYear(),
    month: currentDate.getMonth(),
    day: currentDate.getDay()
  };

  this.employeeLunchEntryForm = this.fb.group({
    date: [currentDateObj, Validators.required]
  });
}

But it gives the following error:

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'is-invalid: null'. Current value: 'is-invalid: false'.

If I do the following, the error goes away and obviously this doesn't solve my problem:

date: [null, Validators.required]

Here's the html part:

<form [formGroup]="employeeLunchEntryForm" 
(ngSubmit)="saveEmployeeLunchInfo()">
        <div class="form-area">
            <div class="row">
              <div class="col-md-8 form-inner-area">
                  <div class="form-group row">
                      <label for="date" class="col-sm-3 col-form-label text-right">Date<span class="text-red">*</span></label>
                      <div class="col-sm-7">
                          <div class="input-group">
                              <div class="input-group-prepend">
                                <span class="input-group-text"><i class="ni ni-calendar-grid-58"></i></span>
                              </div>
                              <input class="form-control datepicker" 
                              [ngClass]="{
                                'is-invalid':
                                employeeLunchEntryForm.get('date').errors &&
                                employeeLunchEntryForm.get('date').touched
                              }"

                              formControlName="date" placeholder="Select date" name="date" 
                              ngbDatepicker #d="ngbDatepicker" (click)="d.toggle()" type="text" />
                              <div
                        class="invalid-feedback"
                        *ngIf="
                        employeeLunchEntryForm.get('date').touched &&
                        employeeLunchEntryForm.get('date').hasError('required')
                        "
                      >
                        Please enter date
                      </div>
                            </div>
                      </div>
                  </div>
              </div>
            </div>
        </div>
</form>

what am I doing wrong? Also please suggest if there is a better of way of setting the current date as selected in NgbDatepicker.

James Z
  • 12,209
  • 10
  • 24
  • 44
Arfizur Rahman
  • 384
  • 4
  • 13

0 Answers0