How to effectively implement “Deferrable Views”

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:

  1. The view is stuck at @placeholder block, when BE throws an error. Means, the view does not show any error message.
  2. 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>;

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật