How to show/hide an element in real time (Blazor)?
I have an image I would like to display only after a user has filled in all text fields.
I have tried using disabled
attribute, but that does not seem to work. Any other insights?
Here is my current code:
<EditForm EditContext="@EditContext" style="max-width:800px;" onkeydown="javascript: DisableEnterKey();">
<FluentValidator />
<img src="images/approval-16-grey.ico" alt="Image" disabled="@OkayDisabled">
<p class="statp">How many families and/or individuals are living on your land?</p><br />
<label class="statlabel" for="amountOfFamilies">Amount of families:</label><br />
<InputNumber id="fams" for="indivNum" class="input" @bind-Value="@familyData.IndividualAmount" onwheel="this.blur()" placeholder="Families..." autofocus />
<ValidationMessage For="() => familyData.IndividualAmount" />
<br /><hr class="statHR" />
<label class="statlabel" for="amountOfIndividuals">Amount of single individuals: </label><br />
<InputNumber id="individuals" for="famNum" class="input" @bind-Value="@familyData.FamilyAmount" onwheel="this.blur()" placeholder="Individuals..."/>
<ValidationMessage For="() => familyData.FamilyAmount" />
<br /><hr class="statHR" />
<label class="statlabel" for="names"> Please enter all of the names here:</label><br />
<InputTextArea id="names" class="textArea" rows="4" cols="18" @bind-Value="@PersonName" placeholder="Names of all individuals..." />
<ValidationMessage For="() => familyData.PersonName" />
</EditForm>
</div>
</ul>
@code
{
private EditContext? EditContext;
public FamilyData Model = new FamilyData();
protected string OkayDisabled { get; set; } = "disabled";
protected override void OnInitialized()
{
EditContext = new EditContext(Model);
EditContext.OnFieldChanged += EditContext_OnFieldChanged;
base.OnInitialized();
}
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
SetOkDisabledStatus();
}
private void EditContext_OnFieldChanged(object? sender, FieldChangedEventArgs e)
{
SetOkDisabledStatus();
}
private void SetOkDisabledStatus()
{
if(EditContext.Validate())
{
OkayDisabled = null;
}
else
{
OkayDisabled = "disabled";
}
}
}
Solution 1:
The hidden
html attribute also works to hide an element.
<p hidden>This paragraph should be hidden.</p>
To bind to Model:
<p hidden="@HideLabel">I am Hidden When HideLabel == true</p>
<p hidden="@(!HideLabel)">I am Hidden when Hidelabel == false</p>
<button @onclick="@Toggle">Show/Hide</button>
@code {
private bool HideLabel {get;set;} = false;
private void Toggle()
{
HideLabel = !HideLabel;
}
}
Solution 2:
Change OkayDisabled
to a bool
, and then around your image do this
@if (!OkayDisabled)
{
<img src=".....whatever" etc />
}
You might also want to add @bind:event="oninput"
wherever you use an @bind
.