Angular2 pipe for custom dates with translation support

I have a goal in mind and here is what I want to achieve:

Imagine having a model for a post that includes a JavaScript Date object. Now, I'd like to display the date in a personalized, easy-to-read format that shows an offset from the current time (like "just now", "about one hour ago", "about two hours ago" etc.).

Although new to TypeScript and Angular2, my research suggests that the most elegant solution would involve creating a custom pipe like this:

@Pipe({name: 'hrTime'})
export class HrTimePipe implements PipeTransform {

    constructor(private translate: TranslateService) {

    }

    transform(val: Date): string {

        // Approximate check if the date was around an hour ago
        let now: Date = new Date();
        now.setMinutes(now.getMinutes() - 90);
        if (val > now) {
            return this.translate.instant("about_1_h_ago");
        }
    }
}

The issue with this method is that the TranslateService's instant() function may not ensure that the translation file is loaded when the pipe is created or used. As a result, my current custom pipe only displays the translation key (as instant() cannot locate the translation).

When dealing with longer time intervals (such as more than a day ago), my pipe should switch to using the date format pipe internally instead of returning a translation key that needs to be piped into translate.

Any suggestions on this matter? Is employing a custom pipe the correct approach for achieving my goal?

Thank you!

Answer №1

For those who are not concerned with external dependencies, consider utilizing the moment pipes available in Angular 2. You can find this implementation at https://github.com/urish/angular2-moment

Answer №2

To enhance the functionality, you could transform it into a modified pipe and output an Observable. This method allows for easy chaining with the async pipe for seamless integration.

In this way, three potential scenarios may arise: - If there is a significant time delay: immediately return the date - If there is a slight delay and the translations are already loaded: promptly translate and return - If there is a brief delay and translations are still loading: wait for the completion of the translation file before returning the correct translation

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

Steps to turn off the creation of "exports.__esModule = true;" and "require('lib');"

Example: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA- ...

Can Angular Universal cater to dynamic content needs?

I am considering using Angular Universal for SEO optimization and social media preview purposes. While I understand that it works well with static content, my concern lies with how it handles dynamic content. Specifically, I want search engines and social ...

Do you believe this problem with transpilation has been properly reported to babel-jest?

I recently encountered a problem in the jest project regarding babel-jest transpilation. I added some code that appeared to be error-free, but caused transpilation to fail completely. Although the issue seemed related to a Typescript Next project, there a ...

The attempt to register a ServiceWorker for the angular scope was unsuccessful

I have encountered various solutions to this issue, some of which are not suitable for Angular and others simply do not work. In my quest to implement the "add to Homescreen" feature, I came across a helpful blog post (https://blog.betapage.co/how-to-add ...

Unleashing the full power of TypeScript: Harnessing Array.prototype.reduce with Generics

Attempting to standardize data using Array.prototype.reduce. Puzzled by how I can bypass "type-checking" in the reduce function. My interfaces: interface Dict<T> { [key:string]: T; } interface InnerData { id: string; value: number; } inter ...

Creating conditional keys using the Zod library based on the value of another key

Incorporating the TMDB API into my project, I am making an effort to enhance type safety by reinforcing some of the TypeScript concepts I am learning. To achieve this, I am utilizing Zod to define the structure of the data returned by the API. Upon invest ...

Utilize the .mat-column-name attributes to apply custom styles to a nested component within Angular Material

Within the Child component, an Angular material table is created with columns passed as input: <table mat-table> <ng-container *ngFor="let col of columns" [matColumnDef]="col"> </table> @Input() columns: string[] T ...

Create a custom class that functions similarly to a dictionary

Is it not feasible to achieve this? interface IMap { [key: string]: string; } class Map implements IMap { public foo = "baz"; } But instead of success, I encounter the error: TS2420:Class 'Map' does not correctly implement 'IMap& ...

The 'this' context setting function is not functioning as expected

Within my Vue component, I am currently working with the following code: import Vue from 'vue'; import { ElForm } from 'element-ui/types/form'; type Validator = ( this: typeof PasswordReset, rule: any, value: any, callback: ...

Issue with Socket.io Client: Consistently receiving error messages for an incorrect

Here is the server-side code: import http from 'http'; import Koa from 'koa'; import { Server } from 'socket.io'; (async () => { const app = new Koa(); var server = http.createServer(app.callback()); var io = new Se ...

What is the best way to selectively pass certain values to the args object?

Is there a way in TypeScript to pass only one argument into args and have other values be default without using "args = {}" or declaring defaults within the function to avoid issues with intellisense? function generateBrickPattern ( wallWidth: number, ...

TS and React: Comparing View['props'] to React's ComponentProps<typeof View>

When dealing with an existing React component (referred to here as View), it appears that there are two methods to determine the type of props if it's not exported. Could someone explain the difference between these two approaches? Using lookup typ ...

Using the $state feature in TypeScript with Svelte 5 for defining class fields

Currently, I have a class implementation as follows: class TestClass { prop = $state('test'); } This code works smoothly in files with the extension .svelte.js, and .svelte using <script lang="js">, but encounters issues in f ...

Display a separate component within a primary component upon clicking a button

Looking to display data from a placeholder module upon component click. As a beginner with React, my attempts have been unsuccessful so far. I have a component that lists some information for each element in the module as a list, and I would like to be ab ...

How to retrieve a value from an Angular form control in an HTML file

I have a button that toggles between map view and list view <ion-content> <ion-segment #viewController (ionChange)="changeViewState($event)"> <ion-segment-button value="map"> <ion-label>Map</ion-label> & ...

Break down and extract elements using typedEvent in TypeScript

Within the external library, there is the following structure: export interface Event extends Log { args?: Result; } export interface TypedEvent<EventArgs extends Result> extends Event { args: EventArgs; } export type InstallationPreparedEven ...

Implementing RTKQuery queryFn in TypeScript: A comprehensive guide

Important update: The issue is now resolved in RTKQuery v2 after converting to TypeScript. See the original question below. Brief summary I am encountering an error while trying to compile the TypeScript code snippet below. Tsc is indicating that the r ...

Outdated compiler module in the latest version of Angular (v13)

After upgrading to Angular 13, I'm starting to notice deprecations in the usual compiler tools used for instantiating an NgModule. Below is my go-to code snippet for loading a module: container: ViewContainerRef const mod = this.compiler.compi ...

Determine Data Types from Text

Developing a game involving client/server communication, where different communication "Channels" with unique names and structures are utilized. To simplify the process of handling these channels and their expected parameters, I created an interface as fol ...

The compilation of Angular8 ngx-bootstrap fails when using the --prod flag

Utilizing angular cli 8.3.8, bootstrap 4.4.4 ngx-bootstrap 5.6.1, During development, everything is functioning properly. However, when I compile with --prod, the errors below occur. It is crucial that we resolve the issues with --prod. The datepicker ...