Sub topic 2
Formatting Dates
This chapter assumes basic TypeScript, Angular components and interpolation, and standalone component imports. Angular pipes transform values for display without changing the component’s raw data.
Formatting dates
DatePipe formats a Date, timestamp, or ISO date string. The first parameter selects the format:
<p>Created: {{ createdAt | date:'mediumDate' }}</p>
<p>Exact time: {{ createdAt | date:'yyyy-MM-dd HH:mm' }}</p>Common formats include short, medium, long, fullDate, and mediumDate. Custom patterns use symbols such as yyyy, MM, dd, HH, and mm.
A date with a time zone can display a different calendar day in the browser’s local zone. Supply a time-zone argument when the display must be consistent:
<p>{{ createdAt | date:'yyyy-MM-dd':'UTC' }}</p>Formatting numbers, percentages and currency
Number pipes accept a digits-info string in the form minimumInteger.minimumFraction-minimumFraction:
<p>{{ amount | number:'1.2-2' }}</p>
<p>{{ completion | percent:'1.0-1' }}</p>
<p>{{ price | currency:'EUR':'symbol':'1.2-2' }}</p>For example, 0.875 becomes 87.5%, and 12 becomes $12.00 under the appropriate locale.
Working with arrays and objects
slice selects part of an array or string. keyvalue turns an object’s properties into entries for iteration. json is useful for temporary debugging.
<p>{{ title | slice:0:30 }}</p>
<ul>
@for (entry of settings | keyvalue; track entry.key) {
<li>{{ entry.key }}: {{ entry.value }}</li>
}
</ul>
<pre>{{ profile | json }}</pre>json should not replace deliberate UI formatting. Object key order can also differ from the order expected by a design.
Displaying asynchronous data
The async pipe subscribes to an Observable or Promise, displays its latest value, and unsubscribes when the view is destroyed:
@if (user$ | async; as user) {
<p>Welcome, {{ user.name }}</p>
} @else {
<p>Loading...</p>
}Exercise
Which expression displays createdAt as a four-digit year, two-digit month, and two-digit day in UTC?
Show answer
{{ createdAt | date:'yyyy-MM-dd':'UTC' }}