This article will show you an example on how list items can be implemented and be made dynamic using components. In the end, you will have a simple user list, where you can edit emails and remove the items.
Since the this is a joined project, of API, class library and client-side blazor, we will have to look at API and the shared class library at the same time. As this is where the data comes from.
Throughout the application, we only use two models - one for user data and one for their bank data.
For test data, we simply have a couple of static lists, in a FakeDatabase class.
For the data to be retrieved, we need a couple of controllers - GetUsers and GetBankDetailsForUser methods.
For the updates, we have two more action methods - DeleteUser and UpdateEmailAsync. The first one removes the user in the fake database list and the second one updates the email.
For the client-side, we simply have to retrieve and display the values. There is no logic on, except for the visual changes.
The main procedures will occur in the list item component. The user data is retrieved in the parent page, but the bank details we retrieve once the user parameter is set. Other than that, the data is properly displayed in the appropriate fields. The fields are actually part of a table, basically the component is a single row for the table.
Getting to the interesting part, you can see how smooth the whole editing approach is. We only need a boolean value and two different arrangements for what user can see. The will either see a button and the value, or an edit field and a button. Once the first button is clicked, the boolean is_editoropened is set to true and therefore the editing view opens up. Then, once the "Done" button is clicked, the application simply send and API request to make the change and displays it.
You may also see that we have an event callback for removal of an item. That will be handled in the parent page, as the item displayed come from a list in the parent page.
For the main page, we first have the main table. Remember, the component is a row of a table and in the main part of the table we generate components using a foreach loop. We have users list, which contain user data and that is passed into each component. We retrieve the items when the page is loaded, so there is really nothing fancy about that. The more interesting part here is the RemoveItem method, which takes the user data and invokes an API call to remove it in our fake database. Once that is done, it simply removes the item from the list, the loop for rows gets re-evaluated and you do not see that item anymore.
As you can see, between the main page and the component, we have quite a few lines of code. So, if nothing else, components will make it more readable.