javascriptblazorblazor-webassemblyblazorise

Is it possible to create a Blazor component on button's onclick event


I am very new with Blazor. Hence all guidance and direction regarding my question is highly appreciated.

I am working on a Blazor page where I have implemented Blazorise open source library to implement <CardDeck>...</CardDeck> in a Page(eg. Parent.razor). Underneath that CardDeck I have implemented a Card inside razor component. And I am binding data objects retrieved from database.

Code for Parent.razor is like below.

    <CardDeck>
          <Button @onclick="SomeMethodToCreateComponent"
          @foreach(var item in List)
          {
             //implementing component page (eg. CardComponent.razor)
             <CardComponent>...</CardComponent>
          }
    </CardDeck>

    @Code{
        public void SomeMethodToCreateComponent()
        {
             //Code to create a component on button onclick
        }
    }

Code for component page (eg. Card.razor)


    <Card>
     <CardBody>
        <CardTitle Size="5">Card title 1</CardTitle>
        <CardText>
            Lorem ipsum
        </CardText>
        </CardBody>
    </Card>

Now there is an enhancement to this functionality. On parent razor page, I have a placed a button. On that button's @onclick event I need to generate a component with <Card>...</Card> hierarchy. Whenever the button in parent page is clicked, a card should be generated. Is it possible?


Solution

  • It is much simpler than you think.

    public void SomeMethodToCreateComponent()
    {
         //Code to create a component on button onclick
         var newItem = ...
         List.Add(newItem);
    } // auto re-render here and the @foreach will create and render the new item
    

    In situations like this it is a good idea to add a key to the loop elements:

      @foreach(var item in List)
      {   
         <CardComponent @key='item'>...</CardComponent>
      }