What is the most effective way to split time into two separate parts?

Suppose a user enters the time as 12:34 and we need to split it into two different parts to save it in an array like [12, 34]. How can this be achieved using Angular?

I attempted to split them but my solutions were unsuccessful! I am currently utilizing <ngx-timepicker-field> in Angular and here is my HTML markup:

<ngx-timepicker-field 
     timepickerClass="custom-timepicker-css"
     [defaultTime]="'00:00'"
     [formControlName]="'start_time'"
     [format]="24"
     [clockTheme]="theme"
></ngx-timepicker-field>

Answer №1

To separate a string value and assign it to a new variable, you can utilize the split function with the following code snippet.

const startValue: string = this.formData.get('start').value;
const splitValues: string[] = startValue.split('-');

By executing the above code, you will have ['abc', '123'] stored in splitValues.

Note: * In this example, this.formData references your FormData object.

Answer №2

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Detecting when users stop scrolling in Angular 5

Is there a way to toggle visibility of a div based on user scrolling behavior? I'd like the div to hide when the user scrolls and reappear once they stop. I've attempted to achieve this effect using @HostListener, but it only seems to trigger wh ...

Securing routes in Angular2 using authguards

Currently, I am working on developing a web application and facing some difficulties with routes. I have created an AuthGuard to determine if a user is logged in or not. However, the issue arises when I try to categorize routes into two types: - Routes th ...

What is the process for dynamically loading a concrete implementation and customizing object creation through parameterization?

Concern I am currently developing a Chrome Extension that is capable of receiving commands and is built using TypeScript. My objective is to separate out concrete implementations of a class into individual files that can be loaded dynamically. Illustrat ...

Having trouble importing a file in TypeScript?

I needed to utilize a typescript function from another file, but I encountered an issue: I created a file called Module.ts with the following code snippet: export function CustomDirective(): ng.IDirective { var directive: ng.IDirective = <ng.IDire ...

Step-by-step guide on deploying Angular Universal

Exploring Angular universal and working on understanding deployment strategies. Check out the Github repository at https://github.com/angular/universal-starter This project includes Angular 2 Universal, TypeScript 2, and Webpack 2. After running the comm ...

Uncheck all boxes except for the required or disabled boxes in Angular

HTML: <mat-selection-list #selectedColumns [(ngModel)] ="selectedOptions"> <div class= "content-section"> <mat-expansion-panel> <mat-expansion-panel-header> ...

Best Practices for Angular (2) Form Validation on the Server Side

Struggling to implement server-side form validation using Angular 2, specifically with the following setup: A basic form with login and password fields linked to the view via ngForm / ngModel directives Template-based form structure Synchronous validatio ...

Unlock the Potential: Empowering Users with Nativescript Firebase Sign

Recently, I embarked on the journey of developing apps using NativeScript and Angular. Looking for a reliable database source, I decided to go with Google Firebase. Successfully migrating my SQL data to the Firebase real-time database, I am now able to s ...

Issue deploying serverless: Module '/Users/.../--max-old-space-size=2048' not found

Everything is running smoothly on my serverless project locally when I use sls offline start. However, when I attempt to deploy it through the command line with serverless deploy, I encounter the following error stack. internal/modules/cjs/loader.js:1030 ...

Leverage the power of Angular by configuring a custom webpack setup to

Implementing the CSS modules concept in my Angular app has been a challenge due to conflicts with existing frontend CSS. My project utilizes SCSS, and I am looking for a way for webpack to modularize the CSS generated from SCSS during the final build step. ...

Troubleshooting ngFor Issue in Angular 4

I've double-checked all the required modules and scanned for errors, but unfortunately, nothing seems to be helping me at the moment. As a newcomer to Angular, I'm still in the learning phase. Now, let's take a look at my app.module.ts file ...

Creating Child Components in Vue Using Typescript

After using Vue for some time, I decided to transition to implementing Typescript. However, I've encountered an issue where accessing the child's methods through the parent's refs is causing problems. Parent Code: <template> <re ...

How come a null variable continues to widen to type any even when strictNullChecks is enabled?

According to the TypeScript Documentation, if strictNullChecks is true, there should be no type widening. Also, the typeof nul should be null. let nul = null; // typeof nul = any let undef = undefined; // typeof undef = any Check it out in the Playground ...

Is there a method to define an 'internal' property within a TypeScript type?

I created a custom 'library' in Angular and TypeScript. This library is distributed as a *.ts package within other Angular workspaces. Within this library, I have an exported class that contains various properties. One specific property in thi ...

Encountering an error where `ng serve` is failing because it cannot locate the local workspace file (`angular.json`) for angular 5

Ensuring I'm in the correct directory. After successfully running `ng serve` earlier today, I am now encountering errors: Local workspace file ('angular.json') could not be found. Error: Local workspace file ('angular.json') coul ...

Creating a TypeScript array of objects that aligns with a specific interface: A step-by-step guide

In the code snippet below, there is a Typescript interface called Product. The goal is to ensure that every object in the products array follows this interface. However, the implementation process has been challenging so far. Various attempts like products ...

What causes the error "property does not exist on type" when using object destructuring?

Why am I encountering an error in TypeScript when using Object destructuring? The JavaScript code executes without any issues, but TypeScript is showing errors. fn error: This expression is not callable. Not all elements of type '(() => void) | ...

Angular @Input set function not being activated during unit testing

Within my Component @Input('price') set setPrice(price) { this.price = price; this.modifyTotalAmount(); } Unit Testing (component.spec.ts) it('should execute function ', () => { spyOn(fixture.componentInstance, ' ...

Angular 16 brings a revolution in routerLink behavior

Previously, when I was using angular < 16, my routes configuration looked like this: { path: Section.Security, canActivate: [AuthGuard, AccessGuard, AdminGuard], children: [ { path: '', pathMatch: 'full', ...

How to declare multiple components in @ngModule using Angular 2

Currently, I'm working on a hefty project that combines Angular 2 with ASP.net MVC. I've got around 120 components declared within the @NgModule block like so: @NgModule({ imports: [CommonModule], declarations: [Component1, Component2, Comp ...