Blazor Tutorial - Build your first Blazor app

Modify a component

Component parameters are specified using attributes or child content, which allow you to set properties on the child component. Define a parameter on the Counter component for specifying how much it increments with every button click:

  • Add a public property for IncrementAmount with a [Parameter] attribute.
  • Change the IncrementCount method to use the IncrementAmount when incrementing the value of currentCount.
Pages/Counter.razor
@page "/counter"

<h1>Counter</h1>

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

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

@code {
    private int currentCount = 0;

    [Parameter]
    public int IncrementAmount { get; set; } = 1;

    private void IncrementCount()
    {
        currentCount += IncrementAmount;
    }
}

In Index.razor, update the <Counter> element to add an IncrementAmount attribute that changes the increment amount to ten.

Pages/Index.razor
@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<Counter IncrementAmount="10" />

Rerun the app. The Index component now has its own counter that increments by ten each time the Click me button is selected, as shown in the following image. The Counter component (Counter.razor) at /counter continues to increment by one.

The homepage now contains a Counter that increments by 10 showing counter at 40.

Continue