Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Blazor Web Development Cookbook

You're reading from   Blazor Web Development Cookbook Tested recipes for advanced single-page application scenarios in .NET 9

Arrow left icon
Product type Paperback
Published in Nov 2024
Publisher Packt
ISBN-13 9781835460788
Length 282 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Pawel Bazyluk Pawel Bazyluk
Author Profile Icon Pawel Bazyluk
Pawel Bazyluk
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Chapter 1: Working with Component-Based Architecture 2. Chapter 2: Synchronous and Asynchronous Data Binding FREE CHAPTER 3. Chapter 3: Taking Control of Event Handling 4. Chapter 4: Enhancing Data Display with Grids 5. Chapter 5: Managing Application State 6. Chapter 6: Building Interactive Forms 7. Chapter 7: Validating User Input Forms 8. Chapter 8: Keeping the Application Secure 9. Chapter 9: Exploring Navigation and Routing 10. Chapter 10: Integrating with OpenAI 11. Index 12. Other Books You May Enjoy

Decoupling components with DynamicComponent

Decoupling is a design principle that enhances the flexibility and maintainability of your applications. It comes down to reducing direct dependencies between various parts of your code. Blazor offers an elegant solution for rendering components dynamically. In this recipe, we’ll explore the strategic use of DynamicComponent. It allows you to render components dynamically at runtime based on certain conditions or parameters. You’re not required to specify the component type in the markup at compile time explicitly. Heads up – most compilation validators won’t apply here.

Let’s implement the fully decoupled and dynamic prompting of success and failure notifications when the user adds a ticket to the cart, based on that ticket’s availability.

Getting ready

Before you dive into implementing DynamicComponent, do the following:

  • Create a Recipe09 directory – this will be your working directory
  • Copy the Offer and Grid components from the Making components generic recipe or copy their implementation from the Chapter01/Recipe08 directory of this book’s GitHub repository
  • Copy the Chapter01/Data directory, which contains the Samples and TicketViewModel objects required in this recipe, next to the working directory

How to do it...

Follow these steps to learn how to create more modular and independent components using DynamicComponent:

  1. Add a new Alerts directory to your project.
  2. Within the Alerts directory, create the AddedToCart and SoldOut components:
Figure 1.9: Project structure with newly added alert components and sample objects

Figure 1.9: Project structure with newly added alert components and sample objects

  1. Navigate to the AddedToCart component and add a successful alert markup:
    <div class="alert alert-success" role="alert">
        Added to cart successfully.
    </div>
  2. Navigate to the SoldOut component. Declare a Tariff parameter and add a danger alert markup by using the Tariff value:
    <div class="alert alert-danger" role="alert">
        Ticket @Tariff is sold out!
    </div>
    @code {
        [Parameter] public string Tariff { get; set; }
    }
  3. Navigate to the Offer component and, in the @code block, declare additional AlertType and AlertParams variables:
    protected Type AlertType;
    protected Dictionary<string, object> AlertParams;
  4. Inside the @code block of Offer, replace the Add() method’s implementation to validate ticket availability and display a designated notification:
    public void Add(TicketViewModel ticket)
    {
        AlertType = ticket.AvailableSeats == 0 ?
            typeof(Alerts.SoldOut) :
            typeof(Alerts.AddedToCart);
        AlertParams = new();
        if (ticket.AvailableSeats == 0)
        {
            AlertParams.Add(
                nameof(ticket.Tariff),
                ticket.Tariff
            );
        }
    }
  5. In the Offer markup, below the existing Grid instance, add a conditional rendering of DynamicComponent while leveraging the resolved values of the AlertType and AlertParams variables:
    @if (AlertType is null) return;
    <DynamicComponent Type="@AlertType"
                      Parameters="@AlertParams" />

How it works...

In step 1, we added an Alerts directory where we could place different alert components. In step 2, we created the AddedToCart and SoldOut components, representing success and failure notifications when adding a ticket to the cart. In step 3, we focused on implementing the AddedToCart component, which renders an alert-success class with an Added to cart successfully message. In step 4, we implemented the SoldOut component, which renders an alert-danger class and renders the sold-out ticket tariff.

In step 5, we added two critical variables that DynamicComponent leverages. The first is AlertType, of the Type type, which determines the type of component to render. The second is AlertParams, a dictionary that allows us to dynamically pass parameter values to the loaded component. In step 6, we resolved the state of the requested ticket. We checked seat availability and decided whether to use the SoldOut or AddedToCart component. When seats are unavailable, we conditionally add the Tariff parameter to our dynamic collection of parameters. Finally, in step 7, we embedded the DynamicComponent component in the Offer markup. If the AlertType value is unset, we skip rendering it. Otherwise, we append the dynamically resolved markup.

Notice that we utilized the built-in typeof() and nameof() functions to declare the type and parameters of the current notification. If you want or need to take decoupling even further, you can initialize them purely from string variables. That’s especially powerful when you’re working in architecture such as micro-frontends.

lock icon The rest of the chapter is locked
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
Banner background image