Baba
Baba

Reputation: 2219

How to generate a Blazor component dynamically on a click of a button?

I am working with Blazor server. I have a ButtonComponent which displays a button and the user can pass in a label as a parameter via a modal window and then click Ok. Once the user clicks Ok, the label typed in gets displayed on the button.

How can I display multiple components vertically(ButtonComponent) when the user clicks the Show Button one at a time?

@page "/tester"

<button type="button" @onclick="() => showSignUpComponent = true">
    Show Button
</button>

@if (showSignUpComponent)
{
    <ButtonComponent label="Search" /> <hr/>
}

@code {
    bool showSignUpComponent;
}

Upvotes: 1

Views: 1974

Answers (1)

Bennyboy1973
Bennyboy1973

Reputation: 4208

Rather than thinking of collections of controls, think of Lists of objects that need to be expressed in markup. So, if you have a collection of Label strings that need buttons, you can do something like:

@page "/btn"

<input @bind="newLabel" />

<button type="button" @onclick="() => Labels.Add(newLabel) ">
    Spawn
</button>

@foreach (var label in Labels)
{
    @*<ButtonComponent label="@label" />*@
    <div>This would be a button with label "@label".</div>
}


@code {
    string newLabel { get; set; } = "";

    List<string> Labels = new List<string>();
}

You can list any class you want, and swap controls in/out as you need.

Upvotes: 2

Related Questions