Multiplying Time in the Format of HH:MM:SS

Three fields are available: "Duration, Repeat, Complete Duration". Users input the duration in the time format (HH:MM:SS) and provide a value for the repeat field such as "5,10,4,9,7, etc." The complete duration field should automatically populate based on the values entered in the first two fields.

I attempted to use Angular's NgModel for both text fields and multiplied the values by the repeat field value. However, I encountered issues with proper conversion.

<div>  
    <input type="value" [(ngModel)]="user.hrDuration"> 
    <input type="value" [(ngModel)]="user.minDuration">
    <input type="value" [(ngModel)]="user.secDuration">
</div>
<div>
 <input type="value"   [(ngModel)]="user.repeat">
</div>
<div>  
    <input type="value" [(ngModel)]="user.hrDuration*user.repeat"> 
    <input type="value" [(ngModel)]="user.minDuration*user.repeat">
    <input type="value" [(ngModel)]="user.secDuration*user.repeat">
</div>

Although I tried this method, it simply multiplied the values directly without proper conversion. My goal is to convert the values first before multiplying them by the repeat field value.

Appreciate any help provided!

Answer №1

If you want to track changes in the input fields, make sure to subscribe to their input events:

<div>  
    <input type="value" [(ngModel)]="user.hrDuration" (input)="updateResult()"> 
    <input type="value" [(ngModel)]="user.minDuration" (input)="updateResult()">
    <input type="value" [(ngModel)]="user.secDuration" (input)="updateResult()">
</div>
<div>
 <input type="value" [(ngModel)]="user.repeat" (input)="updateResult()">
</div>
<div>  
    <input type="text" [ngModel]="result.hrDuration"> 
    <input type="text" [ngModel]="result.minDuration">
    <input type="text" [ngModel]="result.secDuration">
</div>

Then, within the Component, implement a method to handle these input events:

export class AppComponent  {
  user = {
    hrDuration: 1,
    minDuration: 1,
    secDuration: 1,
    repeat: 1
  }

  result = {
    hrDuration: this.user.hrDuration * this.user.repeat,
    minDuration: this.user.minDuration * this.user.repeat,
    secDuration: this.user.secDuration * this.user.repeat
  }

  updateResult() {
    // Perform calculations here
    this.result.hrDuration = this.user.hrDuration * this.user.repeat;
    this.result.minDuration = this.user.minDuration * this.user.repeat;
    this.result.secDuration = this.user.secDuration * this.user.repeat;
  }
}

You can find a working example on StackBlitz: https://stackblitz.com/edit/angular-2aukww

Answer №2

If you want to calculate a result based on user input in Angular, consider using an onchange event listener along with a function to handle the calculation:

HTML:

<div>  
    <input type="value" [ngModel]="user.hours" (ngModelChange)="calculateResult()"> 
    <input type="value" [ngModel]="user.minutes" (ngModelChange)="calculateResult()">
    <input type="value" [ngModel]="user.seconds" (ngModelChange)="calculateResult()">
</div>
<div>
 <input type="value" [ngModel]="user.repeat" (ngModelChange)="calculateResult()">
</div>
<div>  
    <input type="value" (ngModel)="user.result" readonly>
</div>

JS:

function calculateResult() {
    if (isNaN($scope.user.hours) ||
        isNaN($scope.user.minutes) ||
        isNaN($scope.user.seconds) ||
        isNaN($scope.user.repeat)) return $scope.user.result = "";

    var total = ($scope.user.hours*60*60 + $scope.user.minutes*60 + $scope.user.seconds) * $scope.user.repeat;

    var hh = Math.floor(total / (60*60));
    if ( hh < 10 ) hh = '0' + hh;

    var diff = total % (60*60);

    var mm =  Math.floor(diff / 60);
    if ( mm < 10 ) mm = '0' + mm;

    var ss = Math.floor(diff % 60);
    if ( ss < 10 ) ss = '0' + ss;

    $scope.user.result = hh + ':' + mm+ ':' + ss;
    // Alternatively, you can display the result as hours, minutes, and seconds
}

Displaying the result as a single value can make it easier for users to understand the final outcome rather than multiplying each time variable by repeats, which can be confusing.

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

Rendering HTML content in a preformatted <code> tag using Electron

Recently, a brand new electron/angular application was built with the code snippet running in main.ts: win.loadURL(url.format({ pathname: path.join(__dirname, 'dist/index.html'), protocol: 'file:', slashes: true })); After launc ...

Svelte warns of potential undefined Variable when using "bind:this={}"

Whenever I attempt to utilize the bind:this attribute in Svelte, I encounter this message in vscode: 'cardGroup' is possibly 'undefined'.js(18048) Upon execution, the following error arises: TypeError: Cannot read properties of undefin ...

The conversion of the property value from type 'java.lang.String' to the required type 'java.time.LocalDate' failed in the JHipster generated file

I have created the files through JHipster and currently facing an issue when trying to execute a query involving a Date variable. The conversion is failing. Below is my typescript file method that sets the criteria for the search: loadSearchPage(page?: ...

Execute a function for each template or controller when the page loads

I recently developed a function for my application that verifies the users' information. I implemented this in my authentication controller within the $rootScope. However, I am facing an issue where I need to manually invoke this function in all of m ...

What is the best way to employ document.addEventListener in TypeScript?

I am currently learning Ionic v2 and I am using document.addEventListener, but I am encountering errors as shown below: > [11:10:21] ionic-app-scripts 0.0.47 [11:10:21] build dev started ... [11:10:21] clean started ... [11:10:21] clean finished in ...

Remove class using jQuery when clicked for the second time and also disable hover effect on the second click

I'm trying to implement a feature that removes the 'active' class when a checkbox is clicked for the second time, similar to how Pinterest handles checkboxes for Twitter and Facebook. Here's what I have tried so far: $(".add_link_twitt ...

Customized Error Handling Function for Ajax Requests

I have a function that works perfectly, but I need to add six more buttons without repeating code. I want each callback to be customizable, with different text for each scenario (e.g. displaying "Please Log In" if the user is not an admin). How can I make ...

Developing a firestore query using typescript on a conditional basis

I've encountered an issue while attempting to create a Firestore query conditionally. It seems like there's a TypeScript error popping up, but I can't seem to figure out what's causing it. Here's the snippet of my code: const fetch ...

The text in Three.js fails to display

Hey there, I'm relatively new to Three.js and having some trouble getting basic text to render. Most of the solutions I found on StackOverflow seem outdated, so I thought I'd ask here. The code snippet below only results in a black screen. Any he ...

Is it possible to provide a project name when using the angular material schematic?

My latest endeavor involved creating a brand new project workspace and then proceeding to establish an application and library within that workspace. ng new workspace --create-application=false cd workspace ng g library testlibrary ng g application playgro ...

Issue encountered when installing packages with NPM due to a missing first argument

Encountering this issue when attempting to install packages using npm install. Looks like there is a problem with npm. I am currently running Linux Mint 19.3 Cinnamon. npm ERR! Linux 5.4.0-42-generic npm ERR! argv "/usr/bin/node" "/usr/bin ...

The issue of Angular child components rendering before receiving parent data

My current challenge involves a parent component (app.component) making an http request, storing the result in this.stats and then passing it as a prop to the child component (progression.component). The issue arises when my child component tries to render ...

display dynamic graphs using json data from a php backend

I'm having trouble displaying a graph using JSON data in Highcharts. Here is a sample of what I need: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/highcharts/demo/column-rotated-labels/ The file values ...

What is the best way to conceal a div while displaying another div using jQuery?

My goal is to make the element2 div disappear when it is clicked, without showing the element2 div initially. $(".toggle").click(function() { $(".element2").toggle(); }); $(".close").click(function() { $(".element2").hide(); }); <script src="ht ...

Fill the tooltip using JSON retrieved from the data-tooltip attribute of the element

Seeking guidance or resources on a specific task I'm working on. I want to populate a tooltip popup with data based on the hovered elements data-tooltip value, but struggling to find relevant information. I've managed to populate tooltips with J ...

AJAX reconstructs accordion elements and shatters them apart

I've implemented Search & Filter Pro to sort through images on a website. The checkbox filters are contained within accordions. Initially, everything functions correctly when the page loads. However, an issue arises when I click on a filter as it ...

Create an interactive HTML table featuring objects as the selected values

I have been attempting to generate an HTML table that is filled with objects. The goal was to make the table selectable by row (via hover), triggering a function when the row is hovered over. Here are the table headers stored in an array: var topTitles ...

Is there a way to deactivate the toggle button in my code?

<label class="switch switch-yes-no" id="disable_'+id+'" style="margin: 0;font-weight: bold;"> <input class="switch-input" type="checkbox" id="disable_'+id+'" /> <span class="switch-label" data-on="Enabled" data-off="Disab ...

Struggling to make the background image appear full screen on the webpage despite implementing a script

Currently, I am in the process of developing a responsive landing page using Bootstrap 4 and I would like to implement a background that changes every few seconds. Although I have managed to make the images change dynamically, I am facing difficulties inco ...

"Using a regular expression with jQuery's .test method results in a false

Looking for a code that checks if an input value matches a regular expression? Despite expecting the input to return true based on the regex, it always comes back as false. Here's the HTML snippet: <input id="user" type="text" /> And here&apo ...