To add an Update function via HTTP Put, we will follow 5 steps:
1. Add an updateStock method in StockService class.
Open stock.service.ts where the StockService() class is located and create an updateStock() method.
2. Create an updateStock subscriber method.
Just below the Dashboard Component class, create a variable that will hold the ID of the selected stock.
Then write the updateStock method.
3. Create a custom loadDetails() method
Just below the selectedStock variable, we’ll need to create another variable named updateEnabled. Initially, we have to set it to false.
And below the updateStock() method, we’ll create the new loadDetails() method.
4. Add the input fields and an Update button
- First, an Update button to select the stock you want to change inside the ngFor directive for each resource. It just toggles the update field to visible to invisible and vice versa.
- Then a <div> tag is created to contain the update field. The input fields shows the current value of the selected stock and saves the changes you will do via the update button.
Now we can test the our application’s functionality. Save your work first and go back to your browser.
As you can see, when the update button is clicked, the update field appears above the data table. Next let’s see if we can update Tesla Inc.’s name to Tesla Motors.
Since location.reload() command is yet to be added, you may have to manually reload your browser to see the change.
Now that our updateStock method is operational, we may now add CSS styles in our field.
5. Add styles in the Update button and input fields
Go to dashboard.component.html and add these styles on the update buttons and fields
- ‘m-x-auto p-a-2 m-t-2’ changes the padding and margin of the update field.
Then back to dashboard.component.ts, add the command location.reload() to automatically reload the page and display the changes you’ve made when you update an item
Save your work and go back to your browser. And there you have it. A fully customized update function!