Blazor InputText: conditionally rendering an attribute

落花浮王杯 提交于 2020-08-25 04:43:37

问题


Blazor vRC1

I'm looking for a straightforward technique on how to conditionally render an attribute within an <InputText> (or any of the input components for that matter). This used to be simple in MVC Razor, where you'd just write the conditional logic within the @(...) statement. Now, writing @(...) has different meaning in the Razor syntax.

For example, I'd like to conditionally output the autofocus HTML attribute for InputText.

<InputText 
 @bind-Value="@TextProperty"
 @(MyModel.isAutoFocus ? "autofocus" : "") <-  This is invalid razor syntax!
/>

回答1:


You could try below code:

<InputText  @bind-Value="@TextProperty"  autofocus="@(MyModel.isAutoFocus)"  />

Refer to https://github.com/aspnet/AspNetCore/issues/10122




回答2:


This could potentially be achieved with the @attributes tag. See more here

Basically, you can add an @attributes tag to your InputText. This can bind to a parameter, or to a handy little method.

<InputText @bind-Value="@TextProperty" @attributes="HandyFunction()" />

@code{
    Dictionary<string,object> HandyFunction()
    {
        var dict = new Dictionary<string, object>();
        if(MyModel.isAutoFocus) dict.Add("autofocus",true);
        return dict;
    }
}



回答3:


As it turns out, Blazor will not render the attribute if the value of the attribute is false or null

https://docs.microsoft.com/en-us/aspnet/core/blazor/components?view=aspnetcore-3.0#conditional-html-element-attributes

HTML element attributes are conditionally rendered based on the .NET value. If the value is false or null, the attribute isn't rendered. If the value is true, the attribute is rendered minimized.

<InputText @bind-Value="@TextProperty" autofocus="@MyModel.isAutoFocus" />


来源:https://stackoverflow.com/questions/58020174/blazor-inputtext-conditionally-rendering-an-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!