Home > OS >  How to access the last element of a reverse array?
How to access the last element of a reverse array?

Time:01-22

If I have a current array listed in REVERSE by simply changing it in html where it is iterating through the indexes:

arrayName.length - i - 1

How would I be able to access just the last array of the element??? Below is the line of statement I tried which fails since we are iterating through the indexes( getting console.log value through every iteration).

arrayName.length - 1 === i

CodePudding user response:

I think the simplest way to access to last element in array in .html will be: *ngFor="let item of items; let last = last"

CodePudding user response:

You can do something like this:

HTML

<div *ngFor="let item of reverseArray, let i = index">
 {{ 'index: '  i }} {{ i === reverseArray.length -1 ? 'Last element of the reverse array: "'   item   '"' : '"'   item   '"'  }}
</div>

TS:

import { Component, VERSION } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  arrayName = [ 11, 89, 23, 7, 98 ];
  reverseArray = [...this.arrayName].reverse();

  constructor() {
    console.log(this.reverseArray);  
  }
 
}

OUTPUT:

enter image description here

  •  Tags:  
  • Related