About Components

The basic structure of a component in blazor can be segregated into 3 sections as below,

//Directives section
@page "/counter"

//Razor HTML section
<p>Current count: @currentCount</p>
<button class="btn btn-primary" onclick="@IncrementCount">Click me</button>

//Function sections
@functions {
    private int currentCount = 0;
    private void IncrementCount()

Directives section:

The Directive section in a Blazor component is used to configure routing for current component, Imports any external class library or for dependency injection,

  • Routing - @page
  • DI - @inject
  • Import Library - @using

Razor HTML section:

Razor HTML syntax is a combination of C# code with HTML. This section finally renders in the browser.

Function section:

The functions section in a component hold user action functions(Event methods), local variables and properties which passed from/to parent/child components.

Attributes & parameters

Lets understand the basic terminologies used in general for SPA,

<button id="btnClickMe" class="btn btn-primary" 
onclick="@IncrementCount">Click me</button>

Here in the button element, the id, class and onclick are called as HTML attributes.

Similarly the components are defined in the same way as HTML elements,

//Parent Component
@page "/ParentComponent"
<ChildComponent Title="Title from Parent">

Here in Parent Component the Child Component is placed and Title is component attributes

//Child Component
    <p>Title from Parent Component : @Title</p>
@functions {
    private string Title { get; set; }

Here in Child Component the attribute Title matches with property in child component functions section decorated with [Parameter]

Last Updated: 11/9/2019, 11:22:54 AM