Skip to content

Commit 17e9a9a

Browse files
committed
feat: added lazy loading for posts (now loads when card expands)
1 parent 99a3647 commit 17e9a9a

File tree

3 files changed

+607
-626
lines changed

3 files changed

+607
-626
lines changed

Diff for: apps/angular/59-content-projection-defer/src/app/expandable-card.ts

+14-2
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
1-
import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
1+
import {
2+
ChangeDetectionStrategy,
3+
Component,
4+
output,
5+
signal,
6+
} from '@angular/core';
27

38
@Component({
49
selector: 'app-expandable-card',
510
template: `
611
<button
712
class="text-fg-subtle hover:bg-button-secondary-bg-hover active:bg-button-secondary-bg-active focus:outline-button-border-highlight flex w-fit items-center gap-1 py-2 focus:outline focus:outline-2 focus:outline-offset-1"
8-
(click)="isExpanded.set(!isExpanded())"
13+
(click)="toggleExpansion()"
914
data-cy="expandable-panel-toggle">
1015
@if (isExpanded()) {
1116
<svg
@@ -51,4 +56,11 @@ import { ChangeDetectionStrategy, Component, signal } from '@angular/core';
5156
})
5257
export class ExpandableCard {
5358
public isExpanded = signal(false);
59+
60+
expanded = output<boolean>();
61+
62+
toggleExpansion(): void {
63+
this.isExpanded.update((isExpanded) => !isExpanded);
64+
this.expanded.emit(this.isExpanded());
65+
}
5466
}

Diff for: apps/angular/59-content-projection-defer/src/app/page-2.ts

+14-3
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
ChangeDetectionStrategy,
44
Component,
55
ResourceStatus,
6+
signal,
67
} from '@angular/core';
78
import { ExpandableCard } from './expandable-card';
89

@@ -17,7 +18,7 @@ interface Post {
1718
selector: 'app-page-2',
1819
template: `
1920
page2
20-
<app-expandable-card>
21+
<app-expandable-card (expanded)="onExpansion($event)">
2122
<div title>Load Post</div>
2223
<div>
2324
@if (postRessource.isLoading()) {
@@ -36,8 +37,18 @@ interface Post {
3637
imports: [ExpandableCard],
3738
})
3839
export class Page2 {
39-
public postRessource = httpResource<Post[]>(
40-
'https://jsonplaceholder.typicode.com/posts',
40+
// Set this signal to true to start fetching the posts
41+
private readonly $loader = signal(false);
42+
43+
// Fetch posts from the API
44+
public postRessource = httpResource<Post[]>(() =>
45+
this.$loader() ? 'https://jsonplaceholder.typicode.com/posts' : undefined,
4146
);
4247
protected readonly ResourceStatus = ResourceStatus;
48+
49+
onExpansion(isExpanded: boolean) {
50+
if (isExpanded && !this.postRessource.hasValue()) {
51+
this.$loader.set(true);
52+
}
53+
}
4354
}

0 commit comments

Comments
 (0)