How to mark ngbDatepicker Valid in form even when no value is selected

会有一股神秘感。 提交于 2019-12-01 18:36:13

The issue was with how I was initializing the form values. I was setting the default values to empty strings where I should have been initializing the dates to null. So I was doing this:

  replicantForm = this.fb.group({
      name: ['', Validators.required],
      incepdate: '',
      longevity: ''
  })

When I should have been doing this:

  replicantForm = this.fb.group({
      name: ['', Validators.required],
      incepdate: null,
      longevity: ''
  })

Many thanks to @pkozlowski-opensource for the clarification.

In response to the accepted answer and the fact it will not work for subsequent updates, I've used the following hack to make sure the control will be valid if no or an invalid date is inserted.

Pretty nasty to change the value in a validator if you ask me, but get's the job done until the ngb-datepicker sets the value internally.

Custom validator on the desired control:

validateOptionalDate(control: AbstractControl) {
  if (!(control.value instanceof Object) && control.value !== null) {
    control.patchValue(null, {
      onlySelf: true,
      emitEvent: false,
      emitModelToViewChange: true,
      emitViewToModelChange: false
    });
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!