@molecule/app-relative-time-angular

Feature · relative-time · App (browser) · v1.1.2 · Apache-2.0

formatRelativeTime utility + RelativeTime component with auto-refresh

npm install @molecule/app-relative-time-angular

npm · Source on GitHub

How it works

@molecule/app-relative-time-angular is a ready-made relative-time feature for the app (browser) side. It composes the core interfaces it needs, so it works with whichever providers your app has bonded.

import { Component } from '@angular/core'
import { RelativeTime, formatRelativeTime } from '@molecule/app-relative-time-angular'

@Component({
  selector: 'app-activity',
  standalone: true,
  imports: [RelativeTime],
  template: `<time
    mol-relative-time
    [date]="'2024-06-01T10:00:00Z'"
    locale="en-US"
    titleLocale="en-US"
  ></time>`,
})
export class Activity {
  // Utility — one-shot formatting
  readonly label = formatRelativeTime('2024-06-01T10:00:00Z', Date.now(), 'en-US')
  // → "5 minutes ago"
}

Works with: @molecule/app-angular, @molecule/app-ui, @molecule/app-ui-angular

Reference

Angular relative-time formatting.

Exports:

  • formatRelativeTime(date, now?, locale?) — utility using Intl.RelativeTimeFormat.
  • <time mol-relative-time> — live-updating component ("5 minutes ago").

It is the Angular counterpart of @molecule/app-relative-time-react: the same export names, the same props (React names) and the same DOM for the same input.

Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit src/index.ts JSDoc, not this file.

Quick Start

import { Component } from '@angular/core'
import { RelativeTime, formatRelativeTime } from '@molecule/app-relative-time-angular'

@Component({
  selector: 'app-activity',
  standalone: true,
  imports: [RelativeTime],
  template: `<time
    mol-relative-time
    [date]="'2024-06-01T10:00:00Z'"
    locale="en-US"
    titleLocale="en-US"
  ></time>`,
})
export class Activity {
  // Utility — one-shot formatting
  readonly label = formatRelativeTime('2024-06-01T10:00:00Z', Date.now(), 'en-US')
  // → "5 minutes ago"
}

Type

feature

Installation

npm install @molecule/app-relative-time-angular @angular/common @angular/core @angular/platform-browser @molecule/app-angular @molecule/app-ui @molecule/app-ui-angular

API

Interfaces

RelativeTimeProps

Props accepted by the RelativeTime component.

interface RelativeTimeProps {
  /** ISO string, Date, or epoch ms. */
  date: Date | string | number
  /**
   * Locale override. Defaults to the app's active locale (`useLocale()`), so the
   * label follows a locale switch; an explicit `locale` still wins.
   */
  locale?: string
  /** Auto-refresh interval (ms). Defaults to 60_000 (1 min). Set 0 to disable. */
  refreshMs?: number
  /** When provided, renders the absolute date in a `title` attribute for hover tooltip. */
  titleLocale?: string
  /** Extra classes (applies to the surrounding `<time>` element). */
  className?: string
}

Classes

RelativeTime

RelativeTime component.

Live-updating relative time display ("5 minutes ago") that re-computes on a timer. Without a locale input the label formats in the app's active locale (useLocale()), so a locale switch re-words it at once; an explicit locale still wins. The host IS the <time> element (time[mol-relative-time]), matching React's root exactly.

@Component({
  selector: 'time[mol-relative-time]',
  standalone: true,
  inputs: ['date', 'locale', 'refreshMs', 'titleLocale', 'className'],
  host: {
    '[attr.datetime]': 'iso()',
    '[attr.title]': 'title()',
    '[class]': 'className ?? null',
  },
  template: '{{ text() }}',
})
export class RelativeTime implements RelativeTimeProps, OnChanges, OnInit, OnDestroy {
  /** ISO string, Date, or epoch ms. */
  date!: Date | string | number
  /**
   * Locale override. Defaults to the app's active locale (`useLocale()`), so the
   * label follows a locale switch; an explicit `locale` still wins.
   */
  locale?: string
  /** Auto-refresh interval (ms). Defaults to 60_000 (1 min). Set 0 to disable. */
  refreshMs?: number
  /** When provided, renders the absolute date in a `title` attribute for hover tooltip. */
  titleLocale?: string
  /** Extra classes (applies to the surrounding `<time>` element). */
  className?: string

  /** The app's active locale — re-renders on a locale switch; an explicit `locale` input still wins. */
  private readonly language = useLocale()

  /** The clock the last tick (or input change) observed. */
  private readonly clock = signal(Date.now())

  /** The running refresh interval, when one is running. */
  private interval: ReturnType<typeof setInterval> | undefined

  /**
   * The `<time>` element's `datetime` value.
   * @returns The ISO string React writes.
   */
  iso(): string {
    return this.date instanceof Date
      ? this.date.toISOString()
      : typeof this.date === 'string'
        ? this.date
        : new Date(this.date).toISOString()
  }

  /**
   * The absolute-date tooltip, when a `titleLocale` is given.
   * @returns The formatted date, or undefined for no `title` attribute.
   */
  title(): string | undefined {
    return this.titleLocale !== undefined
      ? new Intl.DateTimeFormat(this.titleLocale, {
          dateStyle: 'full',
          timeStyle: 'short',
        }).format(new Date(this.iso()))
      : undefined
  }

  /**
   * The rendered relative text. It formats against the clock signal's
   * committed value — the same "now" React keeps in state — so a tick re-reads
   * the time while an unrelated re-render (or locale switch) keeps the value
   * the last tick observed; the locale signal re-words the label at once.
   * @returns The relative time string.
   */
  text(): string {
    return formatRelativeTime(this.date, this.clock(), this.locale ?? this.language())
  }

  /**
   * Starts the refresh timer for the initial `refreshMs`.
   */
  ngOnInit(): void {
    this.restart()
  }

  /**
   * Restarts the refresh timer when `refreshMs` changes (React re-runs its
   * effect on the same prop).
   *
   * @param changes - The changed inputs.
   */
  ngOnChanges(changes: SimpleChanges): void {
    if (changes['refreshMs']) this.restart()
  }

  /**
   * Stops the refresh timer.
   */
  ngOnDestroy(): void {
    this.stop()
  }

  /**
   * Re-reads the clock and re-creates the refresh interval from `refreshMs`.
   */
  private restart(): void {
    this.stop()
    this.clock.set(Date.now())
    const refreshMs = this.refreshMs ?? 60_000
    if (refreshMs <= 0) return
    this.interval = setInterval(() => {
      this.clock.set(Date.now())
    }, refreshMs)
  }

  /**
   * Stops the running refresh interval, when one is running.
   */
  private stop(): void {
    if (this.interval !== undefined) clearInterval(this.interval)
    this.interval = undefined
  }
}

Functions

formatRelativeTime(input, now, locale)

Formats a date, timestamp, or epoch number as a human-readable relative time string (e.g. "5 minutes ago", "in 3 days") using Intl.RelativeTimeFormat.

function formatRelativeTime(
  input: Date | string | number,
  now?: Date | number,
  locale?: string,
): string

Injection Notes

Requirements

Peer dependencies:

  • @angular/common ^22.0.0
  • @angular/core ^22.0.0
  • @angular/platform-browser ^22.0.0
  • @molecule/app-angular ^3.5.0 || ^4.0.0
  • @molecule/app-ui ^1.0.1
  • @molecule/app-ui-angular ^1.1.0

Runtime Dependencies

  • @angular/common

  • @angular/core

  • @angular/platform-browser

  • @molecule/app-angular

  • @molecule/app-ui

  • @molecule/app-ui-angular

  • Zero molecule wiring required — no ClassMap, no bonds; safe in any Angular tree. <time mol-relative-time> reads the app's active i18n locale through useLocale() (a default English provider serves when none is bonded).

  • Inputs: date (Date | ISO string | epoch ms), locale, refreshMs (default 60000 — pass 0 to disable the per-instance timer, cheaper in long lists), titleLocale (adds an absolute-date title tooltip, formatted in that locale), className.

  • locale defaults to the app's active i18n locale (useLocale()), so the label follows a locale switch; an explicit locale input still wins.

  • When Intl.RelativeTimeFormat is unavailable, fallback strings ("just now", "5m ago") are English-only.