The RemoveAt(i) function will not eliminate

I am facing an issue with the removeAt(i) function in my code. It is not removing the element at the specified index. Can someone guide me on how to properly remove an element from an array? Here is the StackBlitz link for reference

HTML

<form [formGroup]="driverInfoForm">
<div class="row" formArrayName="nameDriver">
<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 d-flex" [formGroupName]="i"
  *ngFor="let driver of nameDriver; let i=index">
  <label>{{i+1}}.Name</label>
  <input class="form-control" type="text" id="name" name="name{{i}}"  formControlName="name" [(ngModel)]="nameDriver[i].name"><br/>
  <label>{{i+1}}.Owner Id</label>
  <input class="form-control" type="text" id="ownerId" name="ownerId{{i}}" inputmode="numeric" dashFormat formControlName="ownerId" maxLength="14">
  <div class="col-2 col-sm-2 col-md-2 col-lg-2 col-xl-2" >
  <div class="form-group mb-0" *ngIf="i !== 0">
    
    <button class="btn btn-danger" (click)="removeDriver(i)">
      Delete
    </button>
  </div>
  <div class="form-group mb-2">
  
    <button *ngIf="i >= 0 && i < 1" type="button" [hidden]="nameDriver.length > 3" (click)="addDriver()" class="btn btn-primary">
      Add
    </button>
  </div>
</div>
</div>
</div>
</form>

Component

removeDriver(i: number) {

    const control = <FormArray>this.driverInfoForm.controls['nameDriver'];
    control.removeAt(i);

  }

Answer №1

It is recommended to avoid using reactive forms and template-driven forms simultaneously.

To do so, start by eliminating ngModel from the HTML template.

Next, switch to utilizing the FormArray control instead of the nameDriver array value.

Create a getter named nameDriverControl within the TypeScript file, which can be used to iterate through the form array in the HTML rather than nameDriver.

component.ts

get nameDriverControl(){
    return this.driverInfoForm.get('nameDriver') as FormArray;
}

component.html

<form [formGroup]="driverInfoForm">
  <div class="row" formArrayName="nameDriver">
    <div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 d-flex" [formGroupName]="i"
      *ngFor="let driver of nameDriverControl.controls; let i=index">
      <label>{{i+1}}.Name</label>
      <input class="form-control" type="text" id="name" name="name{{i}}"  formControlName="name" ><br/>
      <label>{{i+1}}.Owner Id</label>
      <input class="form-control" type="text" id="ownerId" name="ownerId{{i}}" inputmode="numeric" dashFormat formControlName="ownerId" maxLength="14">
      <div class="col-2 col-sm-2 col-md-2 col-lg-2 col-xl-2">
        <div class="form-group mb-0" *ngIf="i !== 0">

          <button class="btn btn-danger" (click)="removeDriver(i)">
      Delete
    </button>
        </div>
        <div class="form-group mb-2">

          <button *ngIf="i >= 0 && i < 1" type="button" [hidden]="nameDriver.length > 3" (click)="addDriver()" class="btn btn-primary">
      Add
    </button>
        </div>
      </div>
    </div>
  </div>
</form>

Modified Example

Answer №2

This issue may not belong to the original poster, but as it currently ranks as the top search result, I feel compelled to share this information in case others encounter a similar strange situation.

It is important to note that removeAt triggers an event that will cause valueChanges to execute. In my case, this inadvertently led to the array being immediately repopulated due to another bug indirectly caused by a listener.

To solve this problem, I had to tweak the listener to prevent unnecessary repopulation of the array. However, depending on your specific scenario, you might need to prevent the event from firing altogether:

const control = <FormArray>this.driverInfoForm.controls['nameDriver'];
control.removeAt(i, { emitEvent: false });

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

How can I restrict the highest possible date selection in reactjs?

I am working on a project that requires users to select dates using datetime-local, but I want to limit the selection to only three months ahead of the current date. Unfortunately, my current implementation is not working as expected. Any assistance woul ...

How Angular services transmit information to components

I have implemented a search field within my top-bar component and I am facing an issue in passing the input value of that search field to another component. Design Search service Top bar component Result component Operation Top bar component receives th ...

Custom objects do not return true for Symbol.hasInstance

The TypeScript playground encounters an issue with the Symbol.hasInstance built-in symbol, while it functions properly for other symbols. Testing other symbol methods such as Symbol.match and Symbol.replace show no problems, but Symbol.hasInstance is not ...

What steps are required to set up a proxy for my HTTP request?

As a beginner in http requests, I am currently exploring how to retrieve data from . Since they do not support CORS, they recommend using a proxy server to access their data. In my Angular project, I have created a service for the http request: import { ...

Tips on integrating library project into angular

I've been encountering a challenge with angular library projects lately. I'm trying to style a project using a global stylesheet while ensuring that the styles only affect the specific project itself. My attempted solution was to create a compone ...

Converting Firebase Querysnapshots into an Array of objects: A step-by-step guide

I am struggling to extract specific teams from a group of teams. It appears that I need to transform the snapshot into the Team object. Is there a simpler way to convert a snapshot into an array? As a beginner in firebase/angular, I may be overlooking some ...

How can we define a member of the ReactElement type within an interface using TypeScript?

In an attempt to restrict a specific type of interface member for <Route ... />, the following code does not seem to be functioning as intended. import React, { ReactElement } from "react"; import { Route, RouteProps } from 'react-rout ...

What is the best way to establish anchors for *ngFor elements in Angular 2 and beyond?

I have a component that displays items using *ngFor. My goal is to scroll down to the element with anchor #3. Here's the code snippet: @Component({ selector: 'my-app', template: ` <button (click)="scroll(3)">scroll 2</butt ...

Using Angular2, you can easily implement property binding on child elements

Consider this basic Angular 2 application Primary component: @Component({ selector: "app" }) @View({ directives: [ChildComponent] template: '<child-component></child-component>' }) export class App {} Child component @ ...

Applying Type Constraints in Typescript Arrays Based on Other Values

Uncertain about how to phrase this inquiry. I have a specific situation where an object is involved. Key1 represents the name, while key2 stands for options. The type of options is determined by the value of the name. The existing solution works fine than ...

The ngModel in Angular 6 did not update the value within the app component

Currently, I am honing my skills in Angular and TypeScript but have encountered a minor issue. Below is the code snippet from my component.html <div> <input [(ngModel)]="mynumber"> N is now {{N}} // some content I want to do with ...

The Discriminate Union is ineffective in handling function arguments

Trying to create a discriminate union type for two potential component props, but encountering issues with passing the argument to the onClick function in this instance: type TLink = { label: string, onClick?: (e: React.MouseEvent<HTMLAnchorElement& ...

(TypeScript) Generate a type based on the input parameter type

Below is the code snippet I am working with: const Settings = { setting1: 10, setting2: true, }; type S = typeof Settings; function Process<M extends keyof S>(input: { option: M; value: S[M] }) { } If I try to call Process with an incorr ...

Organize information in a React table following a predetermined sequence, not based on alphabetical order

As a beginner with React, I'm looking to sort my data by the column "Status" in a specific order (B, A, C) and vice versa, not alphabetically. The data structure looks like this: export interface Delivery { id: number; name: string; amount: num ...

Utilizing a React hook to render and map elements in a function

Can the hook return function be assigned to a render map in React? In this example, we have the socialAuthMethodsMap map with the onClick parameter. I tried to assign the signInWithApple function from the useFirebaseAuth hook, but it violates React's ...

Utilize the fetch function within a React functional component

I have been experimenting with different methods to fetch data only once before rendering, but I am encountering some challenges: It is not possible to call dispatch in componentDidMount as there is a restriction that it can only be done in Functional c ...

Class field type based on generics

Consider the code snippet below in the playground: type AvailableTypes = { 'array': Array<any>; 'string': string; 'object': object; } class Wrapper<T extends keyof AvailableTypes> { // Can be of ...

Validating multiple conditions in Typescript by passing them as function parameters

As a beginner in TS/JS, I am looking to validate multiple conditions passed as arguments to a function. For instance, currently I am verifying the user role name, but in the future, I may need to check other conditions. validateUserDetails(): Promise< ...

Pull in class definitions from the index.js file within the node_modules directory

In my project, I have the package called "diagram-js" in the node_modules. The file node_modules/diagram-js/lib/model/index.js contains multiple class definitions as shown below: /** * @namespace djs.model */ /** * @memberOf djs.model */ /** * The b ...

Implementing experimental decorators and type reconciliation in TypeScript - A step-by-step guide

My basic component includes the following code snippet: import * as React from 'react'; import { withRouter, RouteComponentProps } from 'react-router-dom'; export interface Props { }; @withRouter export default class Movies extends R ...