Skip to content

Commit be11f3b

Browse files
feat: fix change detection bug
1 parent f3be3ee commit be11f3b

File tree

1 file changed

+27
-18
lines changed

1 file changed

+27
-18
lines changed

apps/angular/32-change-detection-bug/src/app/main-navigation.component.ts

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { AsyncPipe, NgFor, NgIf } from '@angular/common';
2-
import { Component, Input, inject } from '@angular/core';
1+
import { AsyncPipe, NgFor } from '@angular/common';
2+
import { Component, inject, Input, Pipe, PipeTransform } from '@angular/core';
33
import { RouterLink, RouterLinkActive } from '@angular/router';
44
import { FakeServiceService } from './fake.service';
55

@@ -36,18 +36,27 @@ export class NavigationComponent {
3636
@Input() menus!: MenuItem[];
3737
}
3838

39+
// other way would be to use trackby
40+
@Pipe({ name: 'memo' })
41+
export class MemoPipe implements PipeTransform {
42+
transform(prop: string): MenuItem[] {
43+
return [
44+
{ path: '/foo', name: `Foo ${prop}` },
45+
{ path: '/bar', name: `Bar ${prop}` },
46+
];
47+
}
48+
}
49+
3950
@Component({
40-
imports: [NavigationComponent, NgIf, AsyncPipe],
51+
imports: [NavigationComponent, AsyncPipe, MemoPipe],
4152
template: `
42-
<ng-container *ngIf="info$ | async as info">
43-
<ng-container *ngIf="info !== null; else noInfo">
44-
<app-nav [menus]="getMenu(info)" />
45-
</ng-container>
46-
</ng-container>
47-
48-
<ng-template #noInfo>
49-
<app-nav [menus]="getMenu('')" />
50-
</ng-template>
53+
@if (info$ | async; as info) {
54+
@if (info !== null) {
55+
<app-nav [menus]="info | memo"></app-nav>
56+
} @else {
57+
<app-nav [menus]="'' | memo"></app-nav>
58+
}
59+
}
5160
`,
5261
host: {},
5362
})
@@ -56,10 +65,10 @@ export class MainNavigationComponent {
5665

5766
readonly info$ = this.fakeBackend.getInfoFromBackend();
5867

59-
getMenu(prop: string) {
60-
return [
61-
{ path: '/foo', name: `Foo ${prop}` },
62-
{ path: '/bar', name: `Bar ${prop}` },
63-
];
64-
}
68+
// getMenu(prop: string) {
69+
// return [
70+
// { path: '/foo', name: `Foo ${prop}` },
71+
// { path: '/bar', name: `Bar ${prop}` },
72+
// ];
73+
// }
6574
}

0 commit comments

Comments
 (0)