Enhancing Angular 6: Transforming the Add Method to Perform Updates on the View

Currently, I am in the process of modifying a collection of data that is being shown on app.component.html

<ul>
<li *ngFor="let data of DataSource"> 
        {{ data.id }} - {{data.title}} 
</li>
</ul>

So far, I have successfully added a new row of data using the method below:

  create() {
    const newPostId = this.postId + 1;
    this.apiService.create(newPostId, this.postTitle, this.postText).subscribe(result => {
      const newId = result['id'];
      this.retrieveData.push({id: newId, title: this.postTitle});
      this.dataCount = this.dataCount + 1;
    }, error => console.log('There was an error: ', error));
  }

This method effectively adds the new data row to the end of the existing list.

Now, my question arises:

In what way can I modify the create() function to update an existing row and reflect these modifications in the app.component.html?

Answer №1

To accomplish the task of locating and updating an item in an array based on its id, you can follow these steps:

this.apiService.update(...).subscribe(response => {
  const updatedItemId: number = response['id'];
  const currentIndex = this.itemsArray.findIndex((item: {id: number}) => item.id === updatedItemId);
  if (currentIndex > -1) {
      // replace the old item with the updated one
      this.itemsArray.splice(currentIndex, 1, {id: updatedItemId, name: this.updatedItemName});
  } else {
     // Handle case where item was not found in the array
  }
}, err => console.log('Error occurred: ', err))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Manipulating objects within arrays in Typescript/Angular with a focus on copying

I'm currently facing issues with filtering an array using an HTML input. Here is the code snippet in question: ngOnInit() { this.dtoService.setJsonResponse(); this.getPool(); } getPool() { this.json = this.dtoService.jsonResponse; ...

Amazon has raised concerns about my use of an incorrect algorithm for signing requests

Need to include the string "AWS4" in my code implementation, which involves Angular and Python. In Python, I calculate the signature and then pass it to the frontend for sending the file to AWS. Here is a snippet of the signature and payload code: signa ...

Is it possible to set up tsc to compile test specifications specifically from a designated directory?

I have been working on integrating e2e tests into an Angular project that was not originally set up with @angular-cli, so I have been manually configuring most of it. Currently, I am trying to define a script in the package.json file to transpile only the ...

Is it possible to invoke a Javascript function from a coffeescript file?

Struggling to invoke a javascript function from a Coffeescript file within my $(document).ready(), but it seems like the function is not being executed. The function I intend to call originates from an external source that I have included in the head sect ...

Do specific elements of typography adjust according to the size of the window?

I'm always amazed by the creative solutions that come out of this community. So I'm reaching out to see if anyone knows a way to achieve something unique with CSS! Specifically, I'm curious if it's possible to make certain horizontal p ...

Issue with Electron-vue: 'compute:' not functioning as expected

My attempt to create a simple example using the element-ui library was not successful. There are two 'switches' with different active state values: 2 and 1. The values of the switches are supposed to be displayed in <p>{{sw1}}</p> and ...

Utilizing Typescript within Visual Studio Code alongside node_modules

I currently have typescript installed and am utilizing the powerful visual code editor. Whenever I attempt to navigate to the definition of a typescript function in the node_modules directory, Visual Studio Code ends up expanding the entire 'node_mod ...

Exploring the World of AJAX with CodeIgniter

I've been on the hunt for a solid working example of using AJAX with Codeigniter, but most resources I've found are outdated. As an AJAX beginner, I'm struggling to find up-to-date tutorials. What I'm aiming for is an input form on a w ...

When refreshing in Angular, the Local Storage service returns an undefined value for the getItem

In an attempt to store a value in localStorage and retrieve it upon refresh, I have developed a local-storage service to set the value by calling the service. When trying to retrieve the value on refresh, I found that my appComponent's ngOnInit metho ...

Exploring various ways to implement HTTP GET requests within the PrimeVue DatatableUsing a mix

I am facing a challenge where I need to use different GET requests to populate my Datatable with data from separate tables in the Database. Despite trying different approaches, I am unable to figure out how to make this work successfully. I have realized t ...

Trouble encountered while trying to dynamically update an array list in ReactJs

Currently, I am immersing myself in learning reactJS by working on a practical example. In this particular example, there is a form textfield that allows users to add an item to an existing array by clicking a button. However, I've encountered a few e ...

Encountering a top-level-await issue while utilizing the NextJS API

Currently, I am in the process of creating an API using NextJS and MongoDB. To start off, I have set up some basic code at the beginning of the API file: const { db } = await connectToDatabase(); const scheduled = db.collection('scheduled'); Fol ...

Is it possible to configure a unique Bearer Access Token in the "angular-oauth2-oidc" library?

For my Facebook login, I have set up a custom endpoint where the client sends the Facebook access token. In my Ionic App, I use the '@ionic-native/facebook/ngx' package to retrieve this token. Within a Laravel Json API controller, I utilize Soci ...

An easy way to adjust the date format when linking a date in ng-model with md-datepicker

<md-input-container> <label>Scheduled Date</label> <md-datepicker ng-model="editVersionCtrl.selectedPlannedDate" ng-change="editVersionCtrl.checkPlannedDate()"> </md-datepicker> </md-input-container> ...

React sends a POST request that returns with an empty body

Greetings, I am currently developing a react/express application. Successfully made a GET request from my server but facing challenges with a POST request. The server returns an empty body despite having body-parser as a dependency and accepting json as co ...

Develop a seamless user experience by creating dynamic forms using Jquery, PHP, and

I have been attempting to create a simple contact form using jQuery, AJAX, and PHP without refreshing the page. Everything seems to be working smoothly except for event.preventDefault(); Here are my files: Contact_engine.php <?php $name = $_POST ...

Predicate returning negative type assertion

I need help writing two Jest functions that can verify if an object is an instance of a specific type or not. The function expectInstanceOf works perfectly, but unfortunately, the function expectNotInstanceOf is not functioning as expected. export functio ...

Using Typescript to resolve a package from a location other than the default node_modules directory

I am currently delving into typescript and eager to start dabbling in creating packages. Here is the current layout of my project: myProject/ ├── node_modules/ ├── src/ │ ├── app │ ├── index.ts │ ├── packages ...

The process of adding to the element is malfunctioning

Here is the HTML code snippet I am working with: <textarea class="input" placeholder="Tap to enter message" maxlength="160"></textarea> <div class="keyboard"> <ul id="special"> <li data-letter="!">!</li> <li ...

What is the best way to tag a function that takes a constructor function type as a parameter?

My dilemma is that I have a few classes and I am trying to create a function that only accepts the classes themselves, not instances of the classes. class Page1 { } class Page2 { } register(Page1); register(Page2); function Register(pageType){..} Can s ...