HtmlAttribute Attribute

Quickly set parameters to add html attribute

Example

Anchor.razor
@inherits BlazorComponentBase

<a @attributes="AdditionalAttributes">@ChildContent</a>

@code{
    [Parameter]public RenderFragment? ChildContent { get; set; }
    [Parameter][HtmlAttribute]public string? Title { get; set; }
    [Parameter][HtmlAttribute("href")]public string? Link { get; set; }
    [Parameter][HtmlAttribute]public LinkTarget Target { get; set; } = LinkTarget.Blank;
    
    public enum LinkTarget
    {
        [HtmlAttrbute("_blank")]Blank,
        [HtmlAttrbute("_parent")]Parent,
        [HtmlAttrbute("_top")]Top,
    }
}
Anchor.cs
public class Anchor : BlazorComponentBase, IHasChildContent
{
    [Parameter]public RenderFragment? ChildContent { get; set; }
    [Parameter][HtmlAttribute]public string? Title { get; set; }
    [Parameter][HtmlAttribute("href")]public string? Link { get; set; }
    [Parameter][HtmlAttribute]public LinkTarget Target { get; set; } = LinkTarget.Blank;
    
    public enum LinkTarget
    {
        [HtmlAttrbute("_blank")]Blank,
        [HtmlAttrbute("_parent")]Parent,
        [HtmlAttrbute("_top")]Top,
    }
}
Index.razor
<Anchor Link="https://github.com" Title="github" Target="LinkTarget.Top">Go Github</Anchor>

<a href="https://github.com" title="github" target="_top">Go Github</a>

For bool type

Support fixed value if true

[Parameter][HtmlAttribute("collapse","toggle")]public bool Collapse { get; set; }
<Component Collapse/>
<div collapse="toggle"></div>

Set true string if value is true

[Parameter][HtmlAttribute("toggle")]public bool Collapse { get; set; }
<Component Collapse/>
<div toggle="true"></div>

For other types

The parameter value could be the value of attribute

[Parameter][HtmlAttribute("href")]public string? Link { get; set; }
<Component Link="www.github.com"/>
<a href="www.github.com"></a>

Last updated