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

100% Statements 11/11
100% Branches 8/8
100% Functions 3/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 42 43 44 45                                                    1x     10x 10x       12x 7x 7x 3x 4x 4x          
/**
 * Copyright (c) Siemens 2016 - 2025
 * SPDX-License-Identifier: MIT
 */
import { Component, OnInit } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { FieldType, FieldTypeConfig } from '@ngx-formly/core';
import { SiTimepickerComponent } from '@siemens/element-ng/datepicker';
 
import { SiValidationErrorIdPipe } from '../../utils';
 
@Component({
  selector: 'si-formly-time',
  imports: [SiTimepickerComponent, ReactiveFormsModule, SiValidationErrorIdPipe],
  template: `<si-timepicker
    [id]="id"
    [hideLabels]="props.timeConfig?.hideLabels ?? true"
    [showMinutes]="props.timeConfig?.showMinutes ?? true"
    [showSeconds]="props.timeConfig?.showSeconds ?? false"
    [showMilliseconds]="props.timeConfig?.showMilliseconds ?? false"
    [showMeridian]="props.timeConfig?.showMeridian"
    [formControl]="formControl"
    [readonly]="props.readonly || false"
    [errormessageId]="id | siValidationErrorId"
  />`
})
export class SiFormlyTimeComponent 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('');
      }
    }
  }
}