'How do I enforce a parameter in a blazor component?

<MyComponent MyParameter="@MyParameter"></MyComponent>

I want the MyComponent tag to throw an error when no value is supplied to MyParameter parameter.



Solution 1:[1]

Both the other answers are valid, but I would do this:

    public override Task SetParametersAsync(ParameterView parameters)
    {
        parameters.SetParameterProperties(this);
        if (MyParameter == null)
            throw new InvalidOperationException($"{nameof(MyComponent)} requires a {nameof(MyParameter)} parameter.");

        return base.SetParametersAsync(ParameterView.Empty);
    }

Why? SetParametersAsync is the entry method called by the Renderer on the component: no component code has been run. If, say you put your checking in OnParametersSet{Async}, you may have tried to use it in OnInitialized{Async} - you haven't told us why it must be set!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MrC aka Shaun Curtis