Build your first web app with ASP.NET Core using Blazor

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.

The following code shows how to achieve that. The highlighted lines show the changes.

Components/Pages/Counter.razor
@page "/counter"
@rendermode InteractiveServer

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">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 Home.razor, update the <Counter> element to add an IncrementAmount attribute that changes the increment amount to ten as shown by the highlighted line in the following code:

Components/Pages/Home.razor
@page "/"

<PageTitle>Home</PageTitle>

<h1>Hello, world!</h1>

Welcome to your new app.

<Counter IncrementAmount="10" />

Apply the change to the app by clicking the Hot Reload button. The Home 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 Home 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