From 42eb04bf5fa667030416f35e5ab32e552ea8b3be Mon Sep 17 00:00:00 2001 From: IrynOoi Date: Sat, 26 Sep 2026 02:58:48 +0800 Subject: [PATCH] refactor: extract heavy computation to pure pipe --- .../8-pure-pipe/src/app/app.component.ts | 17 ++++++++++------- .../src/app/heavy-computation.pipe.ts | 13 +++++++++++++ apps/angular/8-pure-pipe/src/index.html | 1 + apps/angular/8-pure-pipe/src/main.ts | 1 + 4 files changed, 25 insertions(+), 7 deletions(-) create mode 100644 apps/angular/8-pure-pipe/src/app/heavy-computation.pipe.ts diff --git a/apps/angular/8-pure-pipe/src/app/app.component.ts b/apps/angular/8-pure-pipe/src/app/app.component.ts index a1164df21..1ff771712 100644 --- a/apps/angular/8-pure-pipe/src/app/app.component.ts +++ b/apps/angular/8-pure-pipe/src/app/app.component.ts @@ -1,19 +1,22 @@ +// app.component.ts import { ChangeDetectionStrategy, Component } from '@angular/core'; - +import { HeavyComputationPipe } from './heavy-computation.pipe'; @Component({ selector: 'app-root', - changeDetection: ChangeDetectionStrategy.Eager, + standalone: true, + imports: [HeavyComputationPipe], + changeDetection: ChangeDetectionStrategy.Default, template: ` @for (person of persons; track person) { - {{ heavyComputation(person, $index) }} + {{ person | heavyComputation: $index }} } `, }) export class AppComponent { persons = ['toto', 'jack']; - heavyComputation(name: string, index: number) { - // very heavy computation - return `${name} - ${index}`; - } + // heavyComputation(name: string, index: number) { + // // very heavy computation + // return `${name} - ${index}`; + // } } diff --git a/apps/angular/8-pure-pipe/src/app/heavy-computation.pipe.ts b/apps/angular/8-pure-pipe/src/app/heavy-computation.pipe.ts new file mode 100644 index 000000000..7ff793350 --- /dev/null +++ b/apps/angular/8-pure-pipe/src/app/heavy-computation.pipe.ts @@ -0,0 +1,13 @@ +// heavy-computation.pipe.ts +import { Pipe, PipeTransform } from '@angular/core'; + +@Pipe({ + name: 'heavyComputation', + standalone: true, +}) +export class HeavyComputationPipe implements PipeTransform { + transform(name: string, index: number): string { + console.log('触发了复杂计算:', name); + return `${name} - ${index}`; + } +} diff --git a/apps/angular/8-pure-pipe/src/index.html b/apps/angular/8-pure-pipe/src/index.html index c8ee70b97..75848b84a 100644 --- a/apps/angular/8-pure-pipe/src/index.html +++ b/apps/angular/8-pure-pipe/src/index.html @@ -1,3 +1,4 @@ + diff --git a/apps/angular/8-pure-pipe/src/main.ts b/apps/angular/8-pure-pipe/src/main.ts index 63574fdcf..58b80becc 100644 --- a/apps/angular/8-pure-pipe/src/main.ts +++ b/apps/angular/8-pure-pipe/src/main.ts @@ -1,3 +1,4 @@ +// main.ts import { provideZoneChangeDetection } from '@angular/core'; import { bootstrapApplication } from '@angular/platform-browser'; import { AppComponent } from './app/app.component';