I am trying to build a component that takes a list of objects and executes an Action that that is defined inside the object when a html button is clicked in the component. The code here is actually working but raising a warning.
Warning BL0005: Component parameter 'ClickAction' should not be set outside of its component. (18, 17)
I was reading about the problem online and i think one could solve this using an EventCallback instead of an Action. But im not sure how to do that for the given code. And im not sure if that is the best approach here. It should work for void like the method Foo and async like in Foo2.
Any help would be great.
My index file:
@page "/"
<div>
<ActionButtonBar ActionButtons="Actbtns"></ActionButtonBar>
</div>
@code {
List<ActionButton> Actbtns = new();
protected override Task OnInitializedAsync()
{
var somebtns = new List<ActionButton>
{
new()
{
Title = "Action 1",
ClickAction = Foo
},
new()
{
Title = "Action 2",
ClickAction = async () => await Foo2()
}
};
Actbtns.AddRange(somebtns);
return base.OnInitializedAsync();
}
public void Foo() {}
public async Task Foo2() {await Task.CompletedTask;}
}
ActionButtonBar Component
<div id="button-group-container" class="btn-group" role="group" aria-label="Basic example">
@foreach (var button in ActionButtons)
{
<button type="button" class="btn btn-info rounded-pill" onclick="@button.ClickAction">@button.Title</button>
}
</div>
@code {
[Parameter]
public List<ActionButton> ActionButtons { get; set; } = new();
}
The ActionButton
public class ActionButton : ComponentBase
{
public string Title { get; set; } = string.Empty;
[Parameter]
public Action? ClickAction {get; set;}
}
According to your example, ActionButton
is a separate class, it is not a component, so maybe you can remove the [Parameter]
attribute:
public class ActionButton : ComponentBase
{
public string Title { get; set; } = string.Empty;
//[Parameter]
public Action? ClickAction { get; set; }
}
These warnings can be ignored if the [Parameter]
attribute is required and your value will not change:
protected override Task OnInitializedAsync()
{
//#pragma warning disable BL0005
//...
//#pragma warning restore BL0005
}
Note that this does not guarantee that adding or removing components in the render tree will not cause side effects.