I have implemented Deferrable views in my component.
my-component.html:
<div class="my-container">
@for (type of types; track $index) {
<div class="wrapper">
@defer (when beData && beData.length > 0) {
@if (isError()) {
<div class="error-message">
An error occurred while fetching data.
</div>
} @else if (type === "chart") {
<app-child-one></app-child-one>
} @else if (type === "list") {
<app-child-two></app-child-two>
} @else {
<div class="empty-message">No data available.</div>
}
} @placeholder (minimum 2s) {
@if (type === "chart") {
<app-skeleton-one></app-skeleton-one>
} @else if (type === "list") {
<app-skeleton-two></app-skeleton-two>
}
} @loading (after 2s; minimum 1s) {
<mat-spinner diameter="40"></mat-spinner>
} @error {
<div class="error-message">Failed to load the component.</div>
}
</div>
}
</div>
my-component.ts:
@Component({
selector: 'app-my-component',
standalone: true,
imports: [...],
templateUrl: './my.component.html',
styleUrl: './my.component.scss',
})
export class MyComponent implements OnInit, OnDestroy {
public types = ['chart', 'list'];
public beData: BeData[] = [];
public isLoading = signal(false);
public isError = signal(false);
private _destroy$: Subject<boolean> = new Subject<boolean>();
constructor(private myService: MyService) {}
public ngOnInit(): void {
this.fetchData();
}
private fetchData(): void {
this.isLoading.set(true);
this.isError.set(false);
this.myService
.getBeData()
.pipe(
takeUntil(this._destroy$),
catchError((err) => {
console.error('Error fetching data', err);
this.isError.set(true);
return of(err);
}),
finalize(() => this.isLoading.set(false)),
)
.subscribe((data) => {
this.beData = data;
});
}
public ngOnDestroy(): void {
this._destroy$.next(true);
this._destroy$.complete();
}
}
With the current implementation, I am facing 2 problems:
- The view is stuck at @placeholder block, when BE throws an error. Means, the view does not show any error message.
- I do not see rendering/displaying @loading block even after 2s.
How do I effectively implement “Deferrable Vies“?
The thing to know is that this @defer feature exists to help to display large components and page with lots of components. In few cases components can be so heavy that pages are slow to display and users have to wait to interact with the page main features. With @defer, we can load only the most important features and then load others (or not even load them, when not useful). @defer is a new way to lazy load components.
@error is not catching your observable error, it’s not it’s intent. It catches defered component loading issue. So your error is never handled. See https://github.com/angular/angular/issues/53535
An other issue will happen when you’ll refresh displayed data. Once @defer has loaded the component, it won’t display loading/placeholder again, even when the condition gets back to false.
In my opinion, @defer is not the correct tool for your usecase. @defer release announcement has made developpers (at least me) dream too much. @defer seems rarely useful to me, because I’ve never seen a website so heavy, nor so badely designed, that it could bring value.
There are some proposals to add a new workflow to handle observable loading/error here, but it doesn’t exist yet: https://github.com/angular/angular/issues/18509
I’ve made a loading example without the use of @defer, but using @if/@else, which may help you. It works with angular>=18.1 due to the use of @let
html example to load a list
<div style="border: 1px solid lightgrey; padding: 5px; display:flex; flex-direction: column; gap: 15px">
<div>
<button (click)="onClickLoadFruits()">Load fruits</button>
<button (click)="onClickEmptyFruits()">Load empty fruits</button>
</div>
@let fruits = fruits$ | async;
@if (fruits$ === undefined) {
Placeholder until fruit retrieval launch
} @else if (fruits === null) {
<ngx-skeleton-loader count="4" [theme]="{height: '16px', marginBottom:'0px'}" />
<ngx-skeleton-loader count="4" [theme]="{height: '16px', marginBottom:'0px'}" />
} @else if (fruits.length === 0) {
no fruit found
} @else {
@for (fruit of fruits; track fruit.name) {
<div class="flex flex-col">
<span>Fruit: {{ fruit?.name }}</span>
<span>Color: {{ fruit?.color }}</span>
<span>Blablabla blablabla blablabla blablabla</span>
<span>Blablabla blablabla blablabla blablabla</span>
</div>
}
}
</div>
html example to load an object
<div style="border: 1px solid lightgrey; padding: 5px; display:flex; flex-direction: column; gap: 15px">
<div>
<button (click)="onClickLoadFruit()">Load a fruit</button>
<button (click)="onClickLoadNotFoundFruit()">Load not found fruit</button>
</div>
@let fruit = fruit$ | async;
@if (fruit$ === undefined) {
Placeholder until fruits retrieval launch
} @else if (fruit === null) {
<ngx-skeleton-loader count="4" [theme]="{height: '16px', marginBottom:'0'}" />
} @else if (fruit | isEmptyObject) {
no fruit found
} @else {
<div class="flex flex-col">
<span>Fruit: {{ fruit?.name }}</span>
<span>Color: {{ fruit?.color }}</span>
<span>Blablabla blablabla blablabla blablabla</span>
<span>Blablabla blablabla blablabla blablabla</span>
</div>
}
</div>
component ts
export class DemoComponent {
protected fruit$: Observable<Fruit | EmptyObject> | undefined;
protected fruits$: Observable<Fruit[]> | undefined;
protected onClickLoadFruit(): void {
this.fruit$ = of({ name: 'banana', color: 'yellow' }).pipe(delay(5000));
}
protected onClickLoadNotFoundFruit(): void {
this.fruit$ = of({}).pipe(delay(5000));
}
protected onClickLoadFruits(): void {
this.fruits$ = of([
{ name: 'banana', color: 'yellow' },
{ name: 'strawberry', color: 'red' },
]).pipe(delay(5000));
}
protected onClickEmptyFruits(): void {
this.fruits$ = of([]).pipe(delay(5000));
}
}
type Fruit = { name: string; color: string };
empty object pipe, which is used for single object check
@Pipe({
name: 'isEmptyObject',
standalone: true,
})
export class IsEmptyObjectPipe implements PipeTransform {
public transform(value: unknown): boolean {
return typeof value === 'object' && value !== null && Object.keys(value).length === 0;
}
}
and EmptyObject alias type, which is the type of {}
export type EmptyObject = Record<string, never>;