Ad

Search This Blog

Monday, January 2, 2023

Blazor Server - 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.

Pages/Counter.razor

@page "/counter"

<PageTitle>Counter</PageTitle>

<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 as shown by the highlighted line in the following code:

Pages/Index.razor

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

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

<Counter IncrementAmount="10" />

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


Source collected from https://dotnet.microsoft.com/en-us/learn/aspnet/blazor-tutorial/modify


No comments:

Post a Comment