Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
RxJS Cookbook for Reactive Programming

You're reading from   RxJS Cookbook for Reactive Programming Discover 40+ real-world solutions for building async, event-driven web apps

Arrow left icon
Product type Paperback
Published in Mar 2025
Publisher Packt
ISBN-13 9781788624053
Length 310 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Nikola Mitrovic Nikola Mitrovic
Author Profile Icon Nikola Mitrovic
Nikola Mitrovic
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Handling Errors and Side Effects in RxJS 2. Building User Interfaces with RxJS FREE CHAPTER 3. Understanding Reactive Animation Systems with RxJS 4. Testing RxJS Applications 5. Performance Optimizations with RxJS 6. Building Reactive State Management Systems with RxJS 7. Building Progressive Web Apps with RxJS 8. Building Offline-First Applications with RxJS 9. Going Real-Time with RxJS 10. Building Reactive NestJS Microservices with RxJS 11. Index
12. Other Books You May Enjoy

Optimizing loading tab content

When tabs contain complex data or media-rich content, it’s beneficial to load the content of tabs lazily. By doing so, we aim to minimize initial page load times, conserve bandwidth, and ensure a smooth and responsive interface. So, let’s create a component like that.

How to do it…

In this recipe, we’ll have a simple tab group of two tabs. Only when a tab is selected will we lazy-load the component representing the contents of that tab. Each tab is represented in the URL, so whenever we change tabs, we’re navigating to a separate page.

Step 1 – Defining a tab group and an active tab

In our tabs.component.html file, we’ll use the Angular Material tab to represent a tab group in the UI:

<mat-tab-group
    [selectedIndex]="(activeTab$ | async)?.index"
    (selectedTabChange)="selectTab($event)"
>
    <ng-container *ngFor="let tab of tabs">
        <mat-tab [label]="tab.label"></mat-tab>
    </ng-container>
</mat-tab-group>

Now, inside tabs.component.ts, we need to define the activeTab and loading states, as well as the content of a tab stream that we can subscribe to:

activeTab$ = new BehaviorSubject<TabConfig | null>(null);
activeTabContent$!: Observable<
    typeof TabContentComponent |
    typeof TabContent2Component |
    null
>;
loadingTab$ = new BehaviorSubject<boolean>(false);

Now, we can hook into Angular Router events, filter events when navigation ends, and, based on an active URL, mark the corresponding tab as active:

this.router.events.pipe(
    filter((event) => event instanceof NavigationEnd),
    takeUntil(this.destroy$)
).subscribe({
    next: () => {
        const activeTab = this.tabs.find(
            (tab) => tab.route === this.router.url.slice(1)
        );
    this.activeTab$.next(activeTab || null);
    },
});

Step 2 – Loading tab content

Since we know which tab is active, we can start loading the content of that tab:

private loadTabContent(tab: TabConfig) {
    const content$ = tab.route === 'tab1'
    ? of(TabContentComponent)
    : of(TabContent2Component);
    return content$.pipe(delay(1000));
}
this.activeTabContent$ = this.activeTab$.pipe(
    tap(() => this.loadingTab$.next(true)),
    switchMap((tab) =>
        this.loadTabContent(tab!).pipe(
            startWith(null),
            catchError((error) => {
                this.errors$.next(error);
            return of(null);
            }),
        finalize(() => this.loadingTab$.next(false))
        )
    ),
    shareReplay({ bufferSize: 1, refCount: true })
);

Inside the loadTabContent method, we’ll create an Observable out of the Angular component that’s matched based on the current route. Once we’ve done this, we’re ready to stream into the tab content whenever the active tab changes. We can do this by starting the loading state, switching to the stream that’s loading content, and resetting the loading state once the content has arrived.

Now, all we need to do is represent the content in the UI. Back in our tabs.component.html file, we can simply add the following code:

@if (loadingTab$ | async) {
    <p>Loading...</p>
}
<ng-container
    *ngComponentOutlet="activeTabContent$ | async"
></ng-container>

Now, by going to our browser, we’ll see that the content of a tab will only be loaded when we click on that specific tab:

Figure 2.6: Loading tabs
Figure 2.6: Loading tabs

Figure 2.6: Loading tabs

See also

  • The of function: https://rxjs.dev/api/index/function/of
  • The startWith operator: https://rxjs.dev/api/operators/startWith
  • Angular’s Router’ NavigationEnd event: https://angular.dev/api/router/NavigationEnd
  • The Angular Material tab component: https://material.angular.io/components/tabs/overview
You have been reading a chapter from
RxJS Cookbook for Reactive Programming
Published in: Mar 2025
Publisher: Packt
ISBN-13: 9781788624053
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime