Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

368
Visualizações
Set style of html element by targeting it's id in Blazor

Say I have an element in Blazor. I want to set the elements style based on the value of the input field in Blazor. I am aware that you can do this by using if else blocks in the html code however I want to avoid this as it grows the code base extremely quick. A function would be better which evaluates the incoming object and styles it.

for instance if I have the element below which passes a value the value is passed to a function.

<th><InputText placeholder="First Name" id=FirstName @bind-Value="@filterModel.FirstName">First Name</InputText></th>

Function

    private async void UpdateVisibleData(object sender, FieldChangedEventArgs e){
        Console.WriteLine(e.FieldIdentifier.FieldName + " Change Detected");
        var fieldChanged = e.FieldIdentifier.FieldName;
        var IsEmptyString = FindEmptyStringInField(filterModel, fieldChanged);
        if(IsEmptyString){
            element.style.setProperty('--my-variable-name', 'hotpink');
           }
        }

I havent been able to get the style.setproperty part to work. not sure what other methods there are. Open to JSInterop. preferrable though if I can target the style.setproperty function and get this working.

about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

Revised Answer

Or you can use JSInterop like this:

/wwwroot/js/example.js

export function examplefunction (Id, Color) {
    document.getElementById(Id).style.backgroundColor = Color;
}

razor page :

@inject IJSRuntime JS

@code {
    private IJSObjectReference? module;
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            module = await JS.InvokeAsync<IJSObjectReference>("import", "/js/example.js");
        }
    }
    private async void UpdateVisibleData(object sender, FieldChangedEventArgs e){
        var fieldChanged = e.FieldIdentifier.FieldName;
        await module.InvokeVoidAsync("examplefunction", fieldChanged, "hotpink");
    }
}

Original Answer

I would use ? operator to make simple HTML without additional code

<input type="text" placeholder="First Name" id=FirstName @bind=@textInput style='@(String.IsNullOrEmpty(textInput) ? "background-color: hotpink;" : "")' />
about 4 years ago · Santiago Gelvez Relatório

0

This isn't a exact answer by targeting the id. however I did find a workaround for this which isn't too bad for webassembly by passing a conditional function to the style tag on the element. It doesn't grow the code base as much as using if else blocks and declaring individual strings. although still targeting element id based on fieldeventchanges would be less computationally taxing as the conditional function is checked for every statechange on every field which uses it as opposed to only being called on the element id if the condition is met.

html

<th><InputText style="@StyleForEmptyString(filterModel.FirstName)" placeholder="First Name" id=FirstName @bind-Value="@filterModel.FirstName">First Name</InputText></th>

@code{

private string StyleForEmptyString(string fieldValue)
    {
        if (fieldValue == ""){
            return "outline:none; box-shadow:none;";
        }
        return "";
    }```
about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda