Gary
Gary

Reputation: 1

I want to call blazor component dynamically on button click

I have TemplateSlide.razor component like below

<div class="slide-panel">
  <div class="contact-form-content">
          @Content

 </div>
@code
{
[Parameter] public RenderFragment Content { get; set; }
}

I have razor component Comp.razor like following

<TemplateSlide>
<div>Other comp</div>
</TemplateSlide>

I have other menu component that call Comp.razor on button click

 <div class="page-header-buttons">
        <ul>

            <li class="page-header-buttons-items can-add">
                <MainMenuLink Href="" ActiveClass="page-header-active" HrefMatch="MainMenuLinkMatch.Exact">
                    Dashboard
                </MainMenuLink>

                @*<a class="page-header-plus contact" href="#"><i class="fas fa-plus add-new-contact-icon"></i></a>*@
            </li>
            <li class="page-header-buttons-items can-add">
                <MainMenuLink Href="contacts" ActiveClass="page-header-active">
                    Contacts
                </MainMenuLink>
                <a class="page-header-plus contact"   @onclick="@(()=>Show<Comp>())"><i class="fas fa-plus add-new-contact-icon"></i></a>

            </li>
<li class="page-header-buttons-items can-add">
                <MainMenuLink Href="contacts" ActiveClass="page-header-active">
                    Others
                </MainMenuLink>
                <a class="page-header-plus contact"   @onclick="@(()=>Show<Others>())"><i class="fas fa-plus add-new-contact-icon"></i></a>

            </li>
</ul>
    </div>

How can write generic and dynamic Show method for button click?

Upvotes: 0

Views: 3894

Answers (1)

user12228709
user12228709

Reputation:

I learned this yesterday and I am only posting this in case it helps someone.

I have a list of users I display in my Blazor Chat, and the names are actually buttons:

@foreach (SubscriberCallback callback in Names)
{
    <button class="listbutton" @onclick="(Action<EventArgs>) (args => 
    SendPrivateMessageClicked(args, callback.Id))">@callback.Name</button><br />
}

I have this method called SendPrivateMessageClicked, and I need to pass in the Id (Guid) of who to send the message to.

private void SendPrivateMessageClicked(EventArgs args, Guid toId)
{
    // Attempt to find the subscriber
    SubscriberCallback subscriber = SubscriberService.FindSubscriber(toId);

    // Send Private Message Code Removed, but you get the point
}

enter image description here

Css for the link button:

.listbutton
{
    background:none;
    border:none;
    margin:0;
    padding:0;
    cursor: pointer;
    border: none;
    color: limegreen;
    height: 2.4vh;
    font-size: 2vh;
}
.listbutton:focus
{
    outline: none;
}

I love Blazor!

Upvotes: 1

Related Questions