One-way binding with Parameters

At this point we have a component displaying inside a page, but the CurrentCounterValue within the component always shows the value zero. What we really want is for it to show the same value in the parent page.

The first thing we do is edit the Counter page and specify a value for MyFirstComponent.CurrentCounterValue, like so:

<MyFirstComponent CurrentCounterValue=@currentCount/>

Running the app and navigating to the Counter page will now show an error in the browser’s console window.

WASM: System.InvalidOperationException: Object of type ‘OneWayBinding.Client.Components.MyFirstComponent’ has a property matching the name ‘CurrentCounterValue’, but it does not have [ParameterAttribute] or [CascadingParameterAttribute] applied.

This tells us clearly what is missing. To add a parameter to our component we must decorate our component’s property with a [Parameter] attribute.

<div>
    CurrentCounterValue in MyFirstComponent is @CurrentCounterValue
</div>

@code {
    [Parameter]
    public int CurrentCounterValue { get; set; }
}

This informs Blazor we want a parameter on our component that is settable via an HTML attribute. Whenever the source value changes, Blazor ensures the value in the component is updated and the component is re-rendered.

Note: Parameters must be public properties.

Leave a Reply