How do I get a specific instance of a custom Blazor component?

Platform: Blazor| Category : Components, Tips and Tricks

We can define specific instances for custom components by using @ref while defining the component in a Razor file.

In this sample, we have created the component reference for the card components with specific names. Using this reference, we can access the card component properties and modify them. Here we have changed the display property using the component reference.

[Card.razor]
<div class="card mb-3 @display" style="width: 18rem;">
 <div class="card-body">
      @ChildContent
 </div>
</div>

@code {
    string display = "";

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    public void setVisible(bool visible)
    {
        if (visible)
        {
            display = "";
        }
        else
        {
            display = "d-none";
        }
    }
}
[index.razor]

@page "/"

<Card @ref="MyCardControl1">First Card</Card>

<Card @ref="MyCardControl2">Second Card</Card>

<button class="btn btn-primary" @onclick="Hide">Hide card</button>
<button class="btn btn-primary" @onclick="Show">Show card</button>

<button class="btn btn-primary" @onclick="Hide2">Hide card2</button>
<button class="btn btn-primary" @onclick="Show2">Show card2</button>
@code {

    Card MyCardControl1;
    Card MyCardControl2;

    private void Hide()
    {
        MyCardControl1.setVisible(false);
    }
    private void Show()
    {
        MyCardControl1.setVisible(true);
    }

    private void Hide2()
    {
        MyCardControl2.setVisible(false);
    }
    private void Show2()
    {
        MyCardControl2.setVisible(true);
    }
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.