-1

I am able to dynamically Add or Remove multiple input fields, But the issue is once I have added items and enter some values in the input fields and remove it using delete button, values are not getting cleared, i have tried to empty my array for that index as well but it is not working. Any suggestions please?

I appreciate your help!

Here is my html code:

<div class="row">
   <div>
    <button mat-raised-button (click)="test()">Add </button>
   </div>
    <div *ngFor="let value of fieldArray; let i = index">
        <mat-form-field >          
          <input matInput value="{{getDataValue(i)}}" (focusout)="onFocusOut($event)"  name ="test">
          
        </mat-form-field>
        <button mat-raised-button class="btn btn-danger btn-sm "  (click)="remove(i)">Delete</button>
    </div>
</div>  

code in my .ts file:

fieldArray: Array = [];

 remove(i: number) {
    
    this.fieldArray.splice(i,1);
    
  }

test(){        
        this.fieldArray.push(this.fieldArray.length);       
   }
user1989
  • 47
  • 2
  • 7

1 Answers1

0

With TrackBy, Angular is able to detect which items are deleted or added to an array, using a unique identifier. So, only the items added or removed have to be updated in the DOM.

Like below code for view:

<div *ngFor="let value of fieldArray; let i = index; trackBy: trackByFn">

Below code for .ts file:

trackByFn(index, item) {
    return index; // or item.id
} 
Parth M. Dave
  • 853
  • 1
  • 5
  • 16