0

我正在尝试使用以下代码将当前日期设置为在 NgbDatepicker 中选择的日期。(我正在使用反应形式。)

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]
  });
}

但它给出了以下错误:

ERROR 错误:ExpressionChangedAfterItHasBeenCheckedError:表达式在检查后已更改。以前的值:'is-invalid: null'。当前值:'is-invalid: false'。

如果我执行以下操作,错误就会消失,显然这并不能解决我的问题:

date: [null, Validators.required]

这是html部分:

<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>

我究竟做错了什么?另外请建议是否有更好的方法来设置在 NgbDatepicker 中选择的当前日期。

4

0 回答 0