Implementing a getter method can help you access the split value easily!
get splitDate() {
const value = this.formControlItem && this.formControlItem.value;
if (value.includes('AM') || value.includes('PM')) {
const split = value && value.split(':');
const amPm =
(split && split[1] && split[1].substr(-2, split[1].length)) || 'AM';
return value
? [split[0], split[1].substr(0, split[1].length - 2), amPm]
: [];
} else {
return (value && value.split(':')) || [];
}
}
get splitDateWithPadding() {
const value = this.formControlItem && this.formControlItem.value;
if (value.includes('AM') || value.includes('PM')) {
const split = value && value.split(':');
const amPm =
(split && split[1] && split[1].substr(-2, split[1].length)) || 'AM';
const firstPadded = split[0] && split[0].padStart(2, '0');
const split1 = split[1].substr(0, split[1].length - 2);
const secondPadded = split1 && split1.padStart(2, '0');
return value ? [firstPadded, secondPadded, amPm] : [];
} else {
return (value && value.split(':')) || [];
}
}
html
<mat-form-field appearance="outline">
<mat-label>MY FIELD</mat-label>
<input
type="text"
matInput
[ngxMatTimepicker]="timepicker"
[format]="12"
[required]="required"
readonly
[formControl]="formControlItem"
/>
<mat-icon
matPrefix
*ngIf="formControlItem.value && !formControlItem.disabled && !required"
(click)="onClear($event)"
>
close
</mat-icon>
<mat-icon
matSuffix
*ngIf="!formControlItem.disabled"
(click)="openFromIcon(timepicker)"
>schedule</mat-icon
>
</mat-form-field>
<ngx-mat-timepicker
#timepicker
[enableKeyboardInput]="true"
[max]="maxTime"
[min]="minTime"
></ngx-mat-timepicker>
<br />
{{ formControlItem.value | json }}
<br />
<br />
{{ splitDate | json }}
<br />
<br />
{{ splitDateWithPadding | json }}
Check out the updated code on StackBlitz