Search code examples
javascripttypescriptangularjs-directiveangular6angular7

ngfor nested label id increment decrement according to items count


I have a label in which, it mentions the item added or removed by ngFor, I know I can put index but the index goes on without resetting.

Like

Member 1

Member 2 and so on.

But on adding and then removing and then adding again,

It becomes

Member 1

Member 3

I want that count to automatically become, Member 1 and Member 2

Please help, I’ve tried everything.

The add and remove buttons are placed outside of ngFor div, so that they don’t get replicated for every iteration.

   <div formArrayName="demoArray" 
  *ngFor="let arrayItem of arrayItems; let i=index">
     <div> Member {{  i+1 }} </div>
  <input [id]="arrayItem.id" type="checkbox"
     [formControl]="demoArray[i]">
  <label [for]="arrayItem.id" class="array-item-title">
     {{arrayItem.title}}</label>


Solution

  • To achieve expected result, use below option of assingning modified arrray of objects back to original array while deleting and push new object to original array on Add

    component.ts

        import { Component } from '@angular/core';
    
        @Component({
          selector: 'my-app',
          templateUrl: './app.component.html',
          styleUrls: [ './app.component.css' ]
        })
        export class AppComponent  {
          name = 'Angular';
          arrayItems = [
            {id:1},
            {id:2},
            {id:3},
            ]
            delete(item){
              this.arrayItems = this.arrayItems.filter(v => v.id !== item.id)
            }
    add(){
          this.id++;
          this.arrayItems.push({id: this.id})
        }
        }
    

    Sample working code for reference - https://stackblitz.com/edit/angular-lszvvs?file=src/app/app.component.html

    Updated stackblitz with same functionality but with using one Add and one Delete button as requested by SO - https://stackblitz.com/edit/angular-fix4bj?file=src/app/app.component.ts