Angular – How To remove the elements from ngFor

Issue

I am having a Array which has a structure like this:

Names : ["X","y","","Z"];

I have a *ngFor Iterator that display the array elements. I want that – the empty element in the array to be ignored and print output like this :

 1. X
 2. Y
 3. Z

The issue is when I use this code:

<div*ngFor="let child of Names; let bpiIndex = index" class="sub-title _h4">
   <span *ngIf="child">{{bpiIndex + 1}}.{{child}}</span>
</div>

it generates the output like :

1. X
2. Y
4. Z

is there a way that I can control the index so that It can omit the null or empty values in the array (Given that I am trying to do this in template)?

Solution

The problem is you are using the actual index when you should just instantiate a new variable.

let bpiIndex = index

instead of this instantiate bpiIndex to 0 and use var so the value stays between loops

var bpiIndex = 0

You can also buffer a second array filtered by names, so if the values don’t have a name they won’t be part of the second array and render this new list.

CurrentArray : string[] = ["X","y","","Z"];
...
ngOnInit() {
  this.BufferArrayNoNull = this.CurrentArray.filter(i=>i);
}

Answered By – Mr-Programs

Answer Checked By – Mildred Charles (AngularFixing Admin)

Leave a Reply

Your email address will not be published.