Angular – Update Data with HTTP PUT

In the last article, we discussed how to create data with HTTP POST. In this lesson, you will learn how to update data with HTTP Put.

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.

http put

2. Create an updateStock subscriber method.

Just below the Dashboard Component class, create a variable that will hold the ID of the selected stock.

http put

Then write the updateStock method.

http put

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.

http put

And below the updateStock() method, we’ll create the new loadDetails() method.

http put

4. Add the input fields and an Update button

http put

  • 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.

http put

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.

http put

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

http put

  • ‘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

http put

Save your work and go back to your browser. And there you have it. A fully customized update function!

http put

On the last part of this HTTP series, we will talk about how to remove data with HTTP DELETE.

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.