Search code examples
c#razorblazor

Add attribute without value to Blazor component depending on other attribute value


I have this custom component

<label class="btn-svg label-wrapper">
    @Title

    @if (Multiple)
    {
        <InputFile OnChange="@InputFileOnChange" class="custom-input-hide" accept="@FileFilter" multiple/>
    }
    else
    {
        <InputFile OnChange="@InputFileOnChange" class="custom-input-hide" accept="@FileFilter"/>
    }
</label>

@code
{
    [Parameter]
    public string Title { get; set; }

    [Parameter]
    public string FileFilter { get; set; }

    [Parameter]
    public bool Multiple { get; set; }

    [Parameter]
    public EventCallback<InputFileChangeEventArgs> InputFileOnChange { get; set; }

}

How can I rework @if (Multiple) part and add multiple parameter similarly to OnChange="@InputFileOnChange" ?

I tried to add @Multiple string parameter inside InputFile. Like this <InputFile OnChange="@InputFileOnChange" class="custom-input-hide" accept="@FileFilter" @Multiple/>

But then component is not rendering with error - Unhandled exception rendering component: Failed to execute 'setAttribute' on 'Element': '@Multiple' is not a valid attribute name.


Solution

  • You can use

    <InputFile ... multiple="@Multiple" />
    

    When @Multiple is false Blazor will remove the 'multiple' attribute, when it is true it will result in just multiple in the HTML, without the = .

    It works the same for hidden, disabled etc.