Basic Blazor Components


First it is important to know that everything in Blazor is a component.  Razor components and Blazor components are the same and the terms are interchangeable.  Even a full razor page is a component. 

There are 3 types of components in Blazor: 
  1. Inline – The markup and the code are within the same page 
@page "/counter" 

    <section> 
        <h2>Counter</h2> 

        <p>Current count: @currentCount</p> 

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

    </section> 

@code { 
    int currentCount = 0; 

    void IncrementCount() 
    { 
        currentCount++; 
    } 
} 

  1. Code Behind Component – The mark up and the code are in different files.  There are 2 main parts to remember: 
  1. In the code behind have the class inherit from ComponenetBase.  You will need to add the using for Microsoft.AspNetCore.Components 
    public class CounterBase : ComponentBase 
    { 
        public int currentCount = 0; 

        public void IncrementCount() 
        { 
            currentCount++; 
        } 
    } 
  1. In the razor page add @inhert CodeBehindClass.  It is common to name the code behind class the same as the page but with the “Base” suffix.  You can not name the page and the code behind the same.  This will cause a conflict. 
@page "/counterwithcode" 
@inherits CounterBase 

    <section> 
        <h2>Counter with Code Behind</h2> 

        <p>Current count: @currentCount</p> 

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

    </section> 

  1. Class Only – This is were you hand code all the parts.  It is really over kill for most applications so I will not show it here but you can read more about here 

In the code on GitHub you can see the inline and the code behind samples. 

So, with this component model you can create a component library and using it across an application or better yet, across applications.  You can standardize your own set of controls and even sub pages like a data grid, contact us form, about us, etc.  and use them across all your applications.  Hopefully you can see the power of this. 
To create a razor component library, just create a class library and add your razor components to it.  See source code for details. 
Sources: 

Comments

Popular posts from this blog

Yes, Blazor Server can scale!

Blazor new and improved Search Box

Blazor Wizard Step Component