Formatting the string value

Having trouble formatting the input value. Take a look at this code snippet:

<input
  type="text"
  class="form-control"
  name="time"
  formControlName="time"
  (input)="convertToMinute($event.target.value)"
/>

Here is the function in question:

 convertToMinute(value: string) {
    console.log(value);
    let minute = value.slice(0, 2);
    let seconds = value.slice(2, 4);
    let result = minute + ":" + seconds;
    console.log(result);
  }

The issue occurs when entering 500, resulting in 50:0 instead of 05:00. How can this be fixed?

Answer №1

We offer a variety of built-in pipes for easy data manipulation. For more details, you can refer to the documentation provided at https://angular.io/api/common/DatePipe. The 4th option seems to align with what you are searching for.

{{ dateObj | date }}               // output: 'Jun 15, 2015'
{{ dateObj | date:'medium' }}      // output: 'Jun 15, 2015, 9:43:11 PM'
{{ dateObj | date:'shortTime' }}   // output: '9:43 PM'
{{ dateObj | date:'mm:ss' }}       // output: '43:11'

Answer №2

If you need to add padding to a raw value, you can utilize the padStart() method.

For more information on how to use padStart(), check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

let raw_val = '500';

let full_val = raw_val.padStart(4, '0');


let minutes = full_val.slice(0,2);
let seconds = full_val.slice(2);

console.log(`${minutes}:${seconds}`);

The expected output of the code is:

 "05:00"

You can also view and edit this code snippet on JS Bin here: https://jsbin.com/ruyerafepe/edit?js,console

Answer №3

When the input type is text, it seems that the pipe option might not be effective.

 function convertToMinute(value: string) {
       console.log(value);
       let seconds = value.slice(value.length-2, value.length);
       console.log(seconds);
       let minute = '';
       if((value.length-seconds.length)<2) {
         minute = '0'+value.slice(0, 1);
       } else {
         minute = value.slice(0, 2);
       }

       let result = minute + ":" + seconds;
       console.log(result);
  }

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

Looking to build a unique form validator for two inputs? Ensure that one input number is consistently larger than the other with this guide

Is it possible to create a custom form validator with 2 inputs? My goal is to ensure that one input number is always greater than the other. ValidateMaxMin(control: FormControl) { console.log(control.value.productMin); if (control.value.productM ...

Angular: Error when TypeScript object returns an array object value

I have encountered a strange issue where the array value returned as [object Set] when I console log it. It's unclear whether this problem is occurring in the component or the service, but the object values are not being displayed. This issue arises ...

FirebaseJS 4.0 is not compatible with projects created using Angular CLI

Having trouble integrating firebasejs 4.0 into my Angular CLI project. Here are the steps I followed: ng new firebasetest cd firebasetest ng serve ==> works fine After adding this line to index.html: <script src="https://www.gstatic.com/firebasej ...

Transferring information between two pages when a button is clicked in Angular

How can I display hero details on the hero-details page when clicking a button? I'm currently struggling to make it work. When I click the button, the details show up on the hero-list page, but using the routerLink doesn't display the data. I am ...

Updating the Bootstrap entry dynamically within the @NgModule module

My web application has a specific requirement where it can only be accessed through example.com/index.html without any parameters. The backstory behind this restriction is quite lengthy, so let's not delve into that. Within the index.html file, I have ...

Utilize Angular 2 Form Elements Again

I'm currently in the process of working on a project with Angular and I want to make sure that my form components can be used for creating and updating entities seamlessly. Let's say I have a User entity stored on a remote API, and I have a form ...

Update a specific element within Angular framework

Just starting out with angular and facing a seemingly simple issue that I can't seem to solve despite trying various solutions found on SO. I have created a login component where upon submission, the user is redirected to their profile page. While I a ...

Encountering a Validation Error while Creating a Progressive Web App using Ionic CLI

I'm trying to build a simple PWA app using the IONIC Framework, but have been struggling to make it work. I am still new to Ionic and have followed various tutorials from different sources without success. If you want to check out the tutorials I&apo ...

I'm having trouble getting my nav-tab to function properly in Bootstrap 4 when used with Angular 4. Can

I have been attempting to utilize Bootstrap 4 tabs with Angular 4 with the expectation that it would resemble and function similar to this example enter link description here However, my page is displaying like this. https://i.sstatic.net/dymNH.png Here ...

The ESLint tool seems to be struggling to detect the package named "@typescript-eslint/eslint-plugin"

Struggling with getting ESLint to function properly on a new Angular project in VS Code. The error message I keep encountering is about failing to load "@typescript-eslint/eslint-plugin". After spending the past 3 hours troubleshooting, I have searched hig ...

I attempted to unsubscribe from an observable in Angular, but I encountered an error stating that the unsubscribe function does not exist

Here is the code snippet from a components.ts file in an Angular project. I encountered the following error during compilation: ERROR merge/merge.component.ts:75:12 - error TS2551: Property 'unsubscribe' does not exist on type 'Observable& ...

Error encountered during Svelte/Vite/Pixi.js build: Unable to utilize import statement outside of a module

I'm currently diving into a project that involves Svelte-Kit (my first venture into svelte), Vite, TypeScript, and Pixi. Whenever I attempt to execute vite build, the dreaded error Cannot use import statement outside a module rears its ugly head. Desp ...

Can you explain the meaning of `(error: T) => void` in error?

I've come across this particular syntax in a few Typescript libraries and I am trying to grasp its meaning. error?: (error: T) => void I have seen it being used like so: class SomeClass { someFunction(error?: (error: T) => void){ } ...

Using both Typescript and Javascript, half of the Angular2 application is built

My current project is a large JavaScript application with the majority of code written in vanilla JavaScript for a specific platform at my workplace. I am looking to convert this into a web application that can be accessed through a browser. I believe thi ...

Creating custom designs for a HTML button using CSS

Within an HTML form, there are two buttons set up as follows: <button kmdPrimaryButton size="mini" (click)="clickSection('table')">Table View</button> <button kmdPrimaryButton size="mini" (click)=&quo ...

Navigating through complex routes was tricky in Next.js 14 due to the error 404 on hard navigation with

While working on implementing tab groups using Parallel Routes in Next.js 14, I encountered an issue where a 404 page only appears during hard navigation to /gnb/mypage/tab1. The tabs and their navigation function properly on initial render and when switch ...

Learn the process of marking an option as selected within an Angular component

I have an Angular component that displays a question along with a dropdown menu (<select>) to choose from various answers. My goal is to programmatically set one of the options as selected based on certain parameters present in the application' ...

Issue with NPM installation of node module

My angular project includes a package.json file with all the necessary dependencies listed. However, whenever I run "npm install" in the terminal, the packages seem to download correctly and a node module folder is created in my root directory. Strangely ...

Detecting Errors in Angular Components Using Observers

In my component, I have the following code: this.authService.login4(this.email, this.password) .pipe(first()) .subscribe( data => { console.log(data); }, error => { ...

Resetting Cross-Site Request Forgery (CSRF

Struggling to integrate Django's csrf with Angular 6? Check out this insightful thread I came across. It seems that Django changes the token on login, which makes sense as I can register and login using post requests but encounter issues posting after ...