Reputation: 523
I try to show and disable a button by adding "disabled" class in a component (pre-hidden) but failed - it's not working. Where I did wrong ?
Component Button :
<div class="form-group">
<button class="btn btn-primary @disabled">Disable Me</button>
</div>
@code {
string _password;
string disabled = "";
public void Disable()
{
disabled = "disabled";
}
}
Index.razor :
@page "/"
<h1>How to disable button in component ?</h1>
<button class="btn btn-primary" @onclick="ShowAndDisableButton">Show and disable button</button>
@if (show)
{
<ButtonComponent @ref="button"/>
}
@code
{
ButtonComponent button = new();
bool show = false;
void ShowAndDisableButton()
{
show = true;
button.Disable();
}
}
UPDATED : if I change the ShowAndDisableButton code to
async Task ShowAndDisableButton()
{
show = true;
await Task.Delay(TimeSpan.FromMilliseconds(10)); // add this, wait for a while
button.Disable();
}
and change button code in index.razor to
<button class="btn btn-primary" @onclick="()=>ShowAndDisableButton()">Show and disable button</button>
it works. but I don't know why and don't want to use such way, are there any proper way?
Upvotes: 1
Views: 1130
Reputation: 273179
The problem is that button.Disable();
does not cause the normal rerendering.
And it is an overcomoplicated way of doing things.
In the page:
@if (show)
{
<ButtonComponent Disabled="!show" />
}
@code
{
//ButtonComponent button = new();
bool show = false;
void ShowAndDisableButton()
{
show = true;
//button.Disable();
}
}
and the button itself:
<div class="form-group">
<button class="btn btn-primary" disabled="Disabled">Disable Me</button>
</div>
@code {
string _password;
// string disabled = "";
[Parameter] public bool Disabled {get; set; }
}
But you won't be able to use this button.
Upvotes: 1
Reputation: 2080
Use disabled="@disabledState" Where disabledState is a boolean
Upvotes: 0