Creating a custom pipe that converts seconds to hours and minutes retrieved from an API can be achieved by implementing a transformation function

Can someone please provide guidance on creating a custom pipe in Angular 8 that converts seconds to hours and minutes?

Thank you.

<div class="col-2" *ngFor="let movie of moviesList">
  <div class="movie">
    {{ movie.attributes.title }}
    <img [src]="movie.thumbnails.small">
    {{ movie.attributes.duration }} <== second
  </div>
</div>

Answer №1

Develop a custom pipe named FormatTime

format-time.pipes.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'formatTime'})
export class FormatTime implements PipeTransform {
  transform(value: number): string {
    return new Date(value * 1000).toISOString().substr(11, 8)
  }
}

Import and include it in your module declarations

...
import { FormatTime } from './format-time.pipes';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent, FormatTime ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Usage in Template

<div class="col-2" *ngFor="let movie of moviesList">
  <div class="movie">
    {{ movie.attributes.title }}
    <img [src]="movie.thumbnails.small">
    {{ movie.attributes.duration | formatTime }}
  </div>
</div>

Answer №2

You have the ability to create a pipe similar to the one below,

@Pipe({
    name: 'secondsTransform'
})
export class SecondsTransformPipe implements PipeTransform {
    constructor() {}

    transform(value: number): string {
        let minutes: number = Math.trunc(value/60);
        let hours: number = 0;
        let seconds: number = value - (minutes*60);

        if (minutes >= 60) {
          hours = Math.trunc(minutes/60);
          minutes = minutes - (hours*60);
        }

        let response: string = "";

        if (hours > 0) {
          response = response + hours + " hours ";
        } 

        if (minutes > 0) {
          response = response + minutes + " minutes ";
        }

        if (seconds > 0) {
          response = response + seconds + " seconds";
        }

        return response;
    }
}

Import the newly created pipe in the module and utilize it in html as {{seconds|secondsTransform}}

You can take a look at the following example that demonstrates how to use the pipe to display the seconds in Hours/Minutes/Seconds, https://stackblitz.com/edit/angular-ivy-7jte9o

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

The UseEffect Async Function fails to execute the await function when the page is refreshed

Having trouble calling the await function on page refresh? Can't seem to find a solution anywhere. Here's the useEffect Code - useEffect(() => { fetchWalletAddress() .then((data) => { setWalletAddress(data); setLoa ...

A Guide to Parsing JSON Data in JavaScript

I am facing an issue with the JSON received from an AJAX call. The problem lies in the unexpected '\t' after a bullet point, causing a JavaScript error in the JSON.Parse(data.d) function. Can you provide advice on how to address this situati ...

The leaflet_Ajax plugin is constantly searching for the default marker symbol located at js/images/marker-icon.png

Although I'm relatively new to Leaflet, I have experience creating interactive maps in the past. Recently, I've been working on a project involving displaying GPS data from a UAV. The UAV transmits location information to a server, which then ret ...

Using jQuery to create clickable images by enclosing them in an `<a>` tag

How can I make each image with a specific class clickable? I would like jQuery to: Retrieve the src attribute of the image. Enclose the image within an a href tag that includes that src URL. .clickable { padding: 20px; border: 1px ...

Struggling with aligning mat-icon in the center using HTML and CSS?

My issue is that the mat-icon in my generated columns is not center aligned. What could be causing this? When using ngFor to generate my datatable columns dynamically, none of them align correctly. The mat-icon inside my DIV defaults to left alignment. ...

Refresh the page with user input after a button is clicked without reloading the entire page, using Python Flask

My python/flask web page accepts user input and returns it back to the user without reloading the page. Instead of using a POST request, I have implemented Ajax/JavaScript to handle user input, process it through flask in python, and display the result to ...

The control options on the AGM map are experiencing functionality issues

Upon setting the options for agm-maps, I noticed that my options briefly appear and then disappear. This behavior puzzled me, so I decided to create a simple project in Stackblitz to showcase the issue. Below, you'll find the code snippets: code samp ...

Encountering a problem when making a HTTPS GET request to a REST API using

I am currently running an Angular application that utilizes an external API to fetch country ISOs. However, I am encountering an error with the API since it uses HTTPS. Interestingly, when I implement a proxy in my Angular local environment by mapping /is ...

Why is it that using e.preventDefault() does not prevent the link from being followed?

What is the solution to prevent a link from being followed with this specific event handler? http://jsfiddle.net/chovy/rsqH7/1/ <table> <tbody> <tr class="msg"> <header><a href="http://cn ...

Mastering the art of curating the perfect image for your Facebook timeline

Controlling the Like image presented on Facebook timeline can be done using the header element. In my single-page app, I have multiple like buttons, each should be connected to a different image. What is the best way to associate a specific image with e ...

Tailwind does not display font sizes using random values

I am attempting to adjust the size of a span element based on a number from a variable: export default async function Tags() { const tags = await getTags(); return ( <div> <Suspense> <div className="flex flex-wrap ...

Attempting to showcase information in React

Having recently delved into React, I am attempting to display data (within a bootstrap modal) from MongoDB to React using an axios ajax request. Postman indicates everything is correct. However, React throws an error stating "TypeError: this.state.reviews. ...

Multer is experiencing difficulties in uploading files, yet it is not displaying any error messages

When setting up an application to create courses with images, I encountered an issue while using multer for image uploading. Despite adding multer to my route with upload.single('images'), the uploaded images were not appearing in the designated ...

typescript's JSON.stringify function includes internal fields but omits public interface values

I'm currently grappling with some confusion surrounding serialization in TypeScript using JSON.stringify and interfaces. My goal is to create an export format for serializing certain objects back to their server-side representation, focusing solely on ...

Exploring the combination of Angular and Redux on windows devices

Upon running ng serve, I encountered the following error: The class NgRedux<RootState> has been incorrectly implemented as interface ObservableStore<RootState>. The property [Symbol.observable] is missing in type NgRedux<RootState> but i ...

Using ES6 syntax, ignite the React function

Below is the code snippet provided: class Seismo extends Component { constructor(props) { super(props); this.state = { news: "" } this.updateNews = this.updateNews.bind(this) } updateNews = () => { console.log('te ...

What is the best way to create 2 select boxes that will disable each other if they match, and then automatically choose the second option so they do not match

Is there a way to have 2 select boxes automatically change one option to the second option on one box when they match? Instead of using an "alert", I am looking for a function that can automatically update one option in one of the select boxes if they mat ...

update component following an ajax request

I attempted the suggested solutions for similar questions, however, they proved ineffective. Upon inserting data into my database, I am looking to update my component (with the user remaining on the same component). I tried navigating directly to the com ...

Jasmine Destiny - Error Encountered: macroTask 'setTimeout': unable to switch to 'active' state, expecting 'planned' state, but it was 'notScheduled'

I am currently using Angular 7 with the Zone.js version of approximately ~0.8.26. Inside my test.ts file, I have included the import statement for 'zone.js/dist/zone-testing'. Below is a snippet from my spec file: import { HttpClientTestingModul ...

Using ASP.net MVC 4 to Implement Validation with Bootstrap Modal and PartialView

After switching from a simple View with validation to using a bootstrap modal and PartialView in my application, I encountered some issues. The client-side validation no longer works and the server-side validation redirects me to a new page instead of disp ...