Video lecture
Watch on YouTube(opens in a new tab)Sub topic 3
Formatting Values with Pipes
This chapter assumes you know the earlier material: standalone components, bindings, signals, and control flow. It covers the rest of the component toolkit briefly. The example below uses every feature discussed in this chapter.
Pipes
A pipe transforms a value for display: {{ joined | date: 'mediumDate' }}. You must add built-in pipes such as DatePipe, CurrencyPipe, and UpperCasePipe to the component's imports array before you use them. To write a custom pipe, create a class with @Pipe and give it a transform method. Pipes are pure by default, so Angular runs transform again only when the input value changes.
The example
import {
AfterViewInit, ChangeDetectionStrategy, Component, ElementRef,
Pipe, PipeTransform, signal, viewChild
} from '@angular/core';
import { DatePipe, NgTemplateOutlet } from '@angular/common';
@Pipe({ name: 'initials' })
export class InitialsPipe implements PipeTransform {
transform(name: string): string {
return name.split(' ').filter(Boolean).map(p => p[0]).join('').toUpperCase();
}
}
@Component({
selector: 'app-profile',
imports: [DatePipe, InitialsPipe, NgTemplateOutlet],
changeDetection: ChangeDetectionStrategy.OnPush,
host: { '[class.active]': 'active()', '(click)': 'active.set(!active())' },
template: `
<ng-template #badge let-label>
<span class="badge">{{ label }}</span>
</ng-template>
<ng-container *ngTemplateOutlet="badge; context: { $implicit: (name() | initials) }" />
<p>Joined {{ joined | date: 'mediumDate' }}</p>
<input #note placeholder="Note" />
@defer (on viewport) {
<p>Details loaded.</p>
} @placeholder {
<p>Scroll to load details.</p>
}
`,
styles: `
:host { display: block; padding: 1rem; }
:host(.active) { outline: 2px solid teal; }
.badge { font-weight: bold; }
`
})
export class ProfileComponent implements AfterViewInit {
name = signal('Ada Lovelace');
joined = new Date(2024, 0, 15);
active = signal(false);
note = viewChild.required<ElementRef<HTMLInputElement>>('note');
ngAfterViewInit() {
this.note().nativeElement.focus();
}
}How each feature works
- Template reference variables:
#notenames an element so the template can refer to it. - Queries:
viewChildreads elements or components from the component's own template.contentChildreads content that a parent passed in through<ng-content>. Both return signals. - Styling and encapsulation: By default,
ViewEncapsulation.Emulatedscopes styles to the component by adding generated attributes.:hosttargets the component's own element. You can also chooseShadowDomorNone. - ng-template: An
ng-templateblock is not rendered until something uses it.ngTemplateOutletrenders it and passes a context object. In the example,$implicitin that object fillslet-label.ng-containergroups content without adding a DOM element. - Host bindings: The
hostmetadata binds classes, properties, and events on the component's own element. - @defer: This block loads its content lazily when its trigger fires. Here the trigger is
viewport, meaning the section scrolls into view. Standalone components inside the block get split into a separate JavaScript chunk.
Lifecycle hooks
| Hook | Runs when |
|---|---|
| `ngOnChanges` | Input values change |
| `ngOnInit` | Once, after the first inputs are set |
| `ngAfterViewInit` | The view and `viewChild` targets exist |
| `ngOnDestroy` | Before the component is removed |
Change detection and OnPush
Default change detection checks every component after any browser event or async task. With OnPush, Angular checks a component only in these cases:
- An input receives a new reference.
- An event fires inside the component.
- A signal read in its template changes.
Signals make OnPush components reliable, because the signal itself tells Angular the view needs updating.
Exercise
The example focuses note in ngAfterViewInit. Why would ngOnInit not be a reliable place for that code?
Show answer
ngOnInit runs before the view is created, so the input element may not exist yet. The query is guaranteed to resolve only after ngAfterViewInit.