I have created a custom button component in a Blazor Server App as follows:
<button type="button" @attributes="@CustomeAttribute" @onclick="@OnButtonClick" class="styled-btn" style="width: @Width; height: @Height;
border-radius: @BorderRadius;">
<i class="@IconClass" style="font-size: @IconSize; color: @IconColor"></i>
</button>
code {
[Parameter]
public string Width { get; set; }
[Parameter]
public string Height { get; set; }
[Parameter]
public string BorderRadius { get; set; }
[Parameter]
public string IconColor { get; set; }
[Parameter]
public string IconClass { get; set; }
[Parameter]
public string IconSize { get; set; }
[Parameter]
public bool IsDisabled { get; set; }
[Parameter]
public EventCallback<MouseEventArgs> OnButtonClick { get; set; }
public Dictionary<string, object> CustomeAttribute { get; set; }
I use this component in a parent component:
<StyledButton IsDisabled="EqSelectedRowCount == 0 ? true : false" BorderRadius="10px" Width="40px" Height="40px" IconColor="Black" IconSize="20px" IconClass="fa-solid fa-power-off" OnButtonClick="@ToggleEquipmentStatusWarn"></StyledButton>
IsDisabled
value can be changed dynamicall based on some business rules. It can take true
or false
values. I want my button component add disabled
attribute to the button whenever the IsDisabled
value changes to true
.
I studies this post and added the following code to the button component:
private bool _isDisabled;
protected override void OnInitialized()
{
_isDisabled = IsDisabled;
}
protected override void OnParametersSet()
{
if(_isDisabled != IsDisabled)
{
_isDisabled = IsDisabled;
AddDisabledAttribute();
}
}
void AddDisabledAttribute()
{
var dic = new Dictionary<string, object>();
if (_isDisabled)
{
dic.Add("disabled", true);
}
else if (!_isDisabled && dic.ContainsKey("disabled"))
{
dic.Remove("disabled");
}
CustomeAttribute = dic;
}
But It does not work and there should be a better solution. How can disable my button component conditionally?