Operating on an angular table arr with the splicing of an object attribute

Encountering an issue. I have a component with some logic for creating and deleting input fields

.ts

export class AppComponent implements OnInit {
  resource: Resource[] = [];
  fieldId = 0;
  testArr = ['1', '2', '3', '4'];

  ngOnInit() {
    this.resource = this.getResource();
  }

  addRes(resource: Resource) {
    resource.resourceInputFields = ['', ...resource.resourceInputFields];
    console.log(this.resource);
  }

  removeRes(resource: Resource, index: number) {
    resource.resourceInputFields.splice(index, 1);
  }

  getResource(): Resource[] {
    return [
      {
        resourceLink: 'link',
        resourceInputFields: [],
        resourceId: '',
      },
    ];
  }
}

export interface Resource {
  resourceLink: string;
  resourceId: string;
  resourceInputFields: string[];
}

.html

<div *ngFor="let res of resource">
  <a>{{ res.resourceLink }}</a>
  <button class="btn" (click)="addRes(res)">+</button>
  <div class="fields">
    <div *ngFor="let resourceField of res.resourceInputFields; index as i">
      {{ i }}
      <input type="text" [ngModel]="resourceField" />
      <button class="btn" (click)="removeRes(res, i)">-</button>
    </div>
  </div>
</div>

Currently facing an issue where the splice method is behaving like shift, deleting the last element in the array.

I am trying to delete the field corresponding to the position of my plus button. Additionally, if there is any value present in the input field that I am going to delete, I also need to remove that value; StackBlitz

Answer №1

Your issue lies in the usage of ""index as i" as labels in your input array. The minus button removes the correct input element. Check out this updated version with corrected index labels:

Updated Version Link

Dynamic string labels are generated in testArr:

export class AppComponent  {
  name = 'Angular ' + VERSION.major;
   resource: Resource[] = [];
   resourceValues = [];
  fieldId = 0;
  testArr = [];

  ngOnInit() {
    this.resource = this.getResource();
  }

  addRes(resource: Resource) {
    this.resourceValues.push('');
    if (this.testArr.length) {
      this.testArr.push((+this.testArr[this.testArr.length - 1] + 1).toString());
    } else {
      this.testArr.push(0);
    }
    resource.resourceInputFields = ['', ...resource.resourceInputFields];
  }

  removeRes(resource: Resource, index: number) {
    resource.resourceInputFields.splice(index, 1);
    this.testArr.splice(index, 1);
    this.resourceValues.splice(index, 1);
    // console.log(this.resourceValues);
  }

  getResource(): Resource[] {
    return [
      {
        resourceLink: 'link',
        resourceInputFields: [],
        resourceId: '',
      },
    ];
  }
}

In the template, use the array instead of the index as a label:

{{ testArr[i] }}

UPDATE:

Regarding the other question, make sure to use two-way data binding. Instead of [ngModel], use [(ngModel)] and remember to have an editable property to store the input value information (e.g., this.resourceValues in my example).

An example of the revised stackblitz: Revised Stackblitz Example

Reference: Angular Forms Guide

Answer №2

After reviewing your stackbliz project, I can confirm that your code is functioning perfectly. To aid in troubleshooting, I have included some additional code below for your reference.

  modifyResource(resource: Resource) {
    resource.resourceInputFields = [ ""+resource.resourceInputFields.length,...resource.resourceInputFields];
    console.log(resource.resourceInputFields);
  }

  deleteResource(resource: Resource, index: number) {
      resource.resourceInputFields.splice(index, 1);
     console.log(resource.resourceInputFields);
  }

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

Initiate a function following a 3-second click on an image

I'm facing a peculiar challenge with my website - I have an invisible button that needs to be pressed for 3 seconds in order to trigger a specific action. Here is what I've attempted so far: $("#basicChn").on({ mousedown: function() { $ ...

typescript error caused by NaN

Apologies for the repetitive question, but I am really struggling to find a solution. I am facing an issue with this calculation. The parameters a to g represent the values of my input from the HTML. I need to use these values to calculate a sum. When I tr ...

"Utilizing a JavaScript array to track the start of the week and

I am encountering a logic problem with determining the start of the week. Below is a snippet of the code: WeekStarts(WeekN) { let WeekBD = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Sa ...

Retrieve the data set's value upon clicking the button

In this HTML snippet, I am looping over a data set. Upon clicking the button, I aim to retrieve a specific value, such as the id from the data set for use in my TypeScript file. <div *ngFor="let item of assignmentlist; let i = index"> < ...

Is there a way to prevent users from copying data or switching tasks when using my program or website?

Is it feasible to develop a website or application for Windows desktop machines that can remain focused until the user completes a specific task? For instance, if my YYY app/website is open and I require the user to input some text, I want to restrict the ...

Press on the div to reveal its content at the clicked position

Hello, I have a query that I need help with. I currently have a basic table with buttons in columns that act as filters. When you click on one of these buttons, it opens up a form. https://i.sstatic.net/nuEpq.png What I am trying to achieve is to make t ...

Storing props in JSX components using variables in React.jsLearn how to set props in JSX components and

If I have already created a component: class Co extends React.Component { render = () => { const name = this.props.name; return ( <p>Hello, my name is {name}</p> ) } } and stored it in a variable ...

My wish is for the animation to activate when hovering over an "a" element on the progress bar

Below is the HTML and CSS code: .collection-by-brand { position: relative; display: flex; width: 100%; height: auto; justify-content: space-around; flex-wrap: wrap; background: linear-gradient(to bottom, #ffffff, whitesmoke); margin-bo ...

When I set the width of my script to 100% in CSS, it causes the width to become distorted

I encountered an issue with my Div Slider that swaps out Divs on click. When I modified the CSS to include the following: .hslide-item {width: 100%}; The script started ignoring the entire div width. I am looking for a solution where the .hslide-item ca ...

Sharing API types from a NestJs backend to a Vue frontend (or any other frontend) application: Best practices

In my development setup, I have a VueJs and Typescript Front End app along with a PHP server that is in the process of being converted to NestJs. Both of these projects reside in the same Monorepo, allowing me to share types for DTOs between them. I am ex ...

Steps for making a Three.js 3D line collection with specified width and thickness

Is there a way to create a Three.js 3D line series with customizable width and thickness? Although the Three.js line object does have a linewidth attribute, it is not universally supported across all browsers and platforms in WebGL. Here is how you can s ...

What steps should I take to rearrange the tab order of two elements located in the middle of the page?

I have a dynamic web page and I am looking for a way to reorder the tab order of two elements within the content without having to set the tab index for every preceding element. Is there a way to assign a tab index relative to an element's position in ...

conducting thorough analysis for detecting modifications akin to $watchCollection in Angular2

I have a situation where I am passing an array of objects from my parent component to child components. Even when a new item is added to the array or the property of an existing object changes, it fails to trigger the ngOnChanges for the affected component ...

Implementing the Upload Feature using AngularJS

Currently, I'm facing a challenge in implementing an upload button on my webpage using AngularJS and Bootstrap. Specifically, I am having trouble assigning the (upload) function to that button in AngularJS. The goal is for the button to enable users t ...

Testing the units of a system ensures that the flow and data storage are reliable

Currently, I'm facing an interesting challenge when it comes to unit testing and the flux data stores. Because the data stores are singletons that are only instantiated once (upon module import), any changes made during unit tests remain persistent. ...

Add an element to an array and check if it is already present

Hey everyone! I've written some code and need help fixing it so that the if statement works properly when adding the same student. Thanks so much for any assistance! class Student { constructor(name, email, community) { this.name = name; this ...

What is the best way to access the Node.js HelloWorld File that I created with a .js extension?

I am currently going through the materials at "NodeBeginner.org". Despite my limited experience with command line, I am struggling to execute my first file. The only success I've had so far is running "console.log('helloworld');" by typing ...

Is there a way to use jQuery to make a div fade in and toggle over another

I have created a test page and I am looking to achieve a specific effect when the page loads. I want everything on the page to be hidden initially. When I click on the "About" text, I want it to fade in using fadeToggle(); however, when I click on "My work ...

Guide on securely submitting a form to a Django site from an external source

My Django application needs to accept POST requests from another website using HTML and JavaScript. For example, I have mydjangosite.com and smallhtmlsite.com. What I'd like to achieve is: When a user visits smallhtmlsite.com and fills out a form, th ...

Tips for dynamically loading images as needed

I'm working on a simple image zoom jQuery feature using elevateZoom. You can see a Demo example here. The implementation involves the following code: <img id="zoom_05" src='small_image1.png' data-zoom-image="large_image1.jpg"/> <sc ...