Understanding Basic Blazor Components
Exploring Components
In Blazor, a component
refers to a .razor file that may encapsulate a specific, self-contained
functionality (including both code and markup) or may serve as a standalone
page. Additionally, a component has the capability to contain other components.
There are three different
ways we can create a component:
- Using Razor syntax, with code and HTML sharing the same file
- Using a code-behind file together with a .razor file
- Using only a code-behind file
Counter
The counter page displays
a button and a counter, where pressing the button increments the counter. At
the top of the page, the @page directive enables direct routing to the
component. By running the MyBlogServerSide project and add/counter to the URL,
we can access the component directly via its route. The implementation of the
counter component is consistent for both Blazor WebAssembly and Blazor Server.
In contrast, the FetchData component has two distinct implementations since the
Blazor Server project can connect directly to server data, whereas Blazor
WebAssembly must access it through a web API. We apply the same methodology
with our API, allowing us to understand how to utilize Dependency Injection
(DI) and directly connect to a database when using Blazor Server.
FetchData
The FetchData component
can be found in the Pages/FetchData.razor directory. The core implementation of
the FetchData component is similar for both Blazor WebAssembly and Blazor
Server. However, the initial lines of the files and the method of retrieving
data vary between the two versions. It establishes a route, includes a
namespace, and injects a service. This service is located in the Data folder of
the MyBlogServerSide project.
Conclusion
Some of the components
that comes with Blazor template are explored.
Comments
Post a Comment