Kurs Angular · Moduł 14: Zaawansowane wzorce
Własne Pipes
W tej lekcji4
Pipes transformują dane w szablonach - jak mistrzowski rzemieślnik wygładza ostrze miecza.
Prosty Pipe
@Pipe({
name: 'truncate',
standalone: true
})
export class TruncatePipe implements PipeTransform {
transform(value: string, limit = 50, trail = '...'): string {
if (!value) return '';
if (value.length <= limit) return value;
return value.substring(0, limit) + trail;
}
}
// Użycie
<p>{{ longText | truncate }}</p>
<p>{{ longText | truncate:100:'...' }}</p>Pipe z Dependency Injection
@Pipe({
name: 'relativeTime',
standalone: true
})
export class RelativeTimePipe implements PipeTransform {
private locale = inject(LOCALE_ID);
transform(value: Date | string): string {
const date = new Date(value);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);
if (diffMins < 1) return 'teraz';
if (diffMins < 60) return `${diffMins} min temu`;
if (diffHours < 24) return `${diffHours} godz. temu`;
if (diffDays < 7) return `${diffDays} dni temu`;
return date.toLocaleDateString(this.locale);
}
}Async Pipe alternatywa
@Pipe({
name: 'safeAsync',
standalone: true,
pure: false // Impure - sprawdza przy każdym change detection
})
export class SafeAsyncPipe implements PipeTransform, OnDestroy {
private subscription?: Subscription;
private latestValue: any = null;
transform<T>(obs: Observable<T>, defaultValue: T): T {
if (!this.subscription) {
this.subscription = obs.subscribe(value => {
this.latestValue = value;
});
}
return this.latestValue ?? defaultValue;
}
ngOnDestroy(): void {
this.subscription?.unsubscribe();
}
}
// Użycie
<p>{{ data$ | safeAsync:'Ładowanie...' }}</p>Filter Pipe
@Pipe({
name: 'filter',
standalone: true
})
export class FilterPipe implements PipeTransform {
transform<T>(items: T[], predicate: (item: T) => boolean): T[] {
if (!items || !predicate) return items;
return items.filter(predicate);
}
}
// Użycie z funkcją
<div *ngFor="let samurai of samuraiList | filter:isActive">
{{ samurai.name }}
</div>Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Jaka jest różnica między pure a impure pipe?
2. Który interfejs musi implementować klasa pipe i jaką metodę wymusza?
Zadania praktyczne w grze
- Układanie w poziomie
Ułóż wyrażenie wywołujące pipe truncate z limitem 100 w szablonie (jedna linia, od lewej):
- Edytor kodu
Uzupełnij custom pipe skracający tekst do określonej długości.
- Klikanie w kolejności
Kliknij elementy w kolejności, aby zbudować początek dekoratora pipe: @Pipe({
- Układanie w pionie
Uporządkuj kolejne linie definicji pipe truncate (od góry do dołu):