All files / formly/fields/datetime si-formly-datetime.component.ts

90.9% Statements 10/11
100% Branches 8/8
66.66% Functions 2/3
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41                                            1x     7x 7x       7x 7x 7x 4x 3x 1x          
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { Component, OnInit } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { FieldType, FieldTypeConfig } from '@ngx-formly/core';
import { SiCalendarButtonComponent, SiDatepickerDirective } from '@siemens/element-ng/datepicker';
 
import { SiValidationErrorIdPipe } from '../../utils';
 
@Component({
  selector: 'si-formly-datetime',
  imports: [
    FormsModule,
    ReactiveFormsModule,
    SiCalendarButtonComponent,
    SiDatepickerDirective,
    SiValidationErrorIdPipe
  ],
  templateUrl: './si-formly-datetime.component.html'
})
export class SiFormlyDateTimeComponent extends FieldType<FieldTypeConfig> implements OnInit {
  ngOnInit(): void {
    // if the date value is in string then first convert it into date
    this.convertValidStringToDate();
    this.formControl.registerOnChange(() => this.convertValidStringToDate());
  }
 
  private convertValidStringToDate(): void {
    if (this.formControl && !(this.formControl.value && this.formControl.value instanceof Date)) {
      const dateVal = new Date(this.formControl.value);
      if (!isNaN(dateVal.valueOf())) {
        this.formControl.setValue(dateVal);
      } else if (this.formControl.value !== '') {
        this.formControl.setValue('');
      }
    }
  }
}