Search code examples
angularbootstrap-4datepickerngb-datepicker

Why does the input ngbDatepicker convert numbers to dates?


In this HTML code, on input number "2", it automatically converts it to 04.01.2001:

 <div class="input-group">
            <input
              [ngClass]="{'invalid-input': editForm.get('birthDate')!.invalid,
                        'valid-input':  editForm.get('birthDate')!.valid}"
              #birthDateDp="ngbDatepicker"
              [disabled]="isAutocomplete"
              [maxDate]="constants.maxDate"
              class="form-control form-control-sm"
              data-cy="birthDate"
              formControlName="birthDate"
              id="field_birthDate"
              name="birthDate"
              ngbDatepicker
              placeholder="{{ 'placeholder.birthDate' | translate }}"
              type="text"
            />
            <button tabindex="-1" (click)="birthDateDp.toggle()" class="btn date-pick btn-secondary" type="button">
              <fa-icon icon="calendar-alt"></fa-icon>
            </button>
          </div>

I tried to catch it's input with

(input)="onDateInput($event, 'birthDate')"

but it retuns a normal input value of type number.


Solution

  • Prevent input value conditions in NgbDateParserFormatter (value.lenght <= 7, in my case).

        @Injectable()
        export class DateInputFormatter extends NgbDateParserFormatter {
          public parse(value: string): NgbDateStruct | null {
            if (!value || value.length <= 7) return null;
        
            const date = dayjs(value);
        
            return {
              year: date.year(),
              month: date.month(),
              day: date.day(),
            };
          }
        }