0

I have a value of type number, I want to decrease it's value by iterating using ngFor.

<div *ngFor="let i of j">
    {{i}}
</div>
R. Richards
  • 24,603
  • 10
  • 64
  • 64

3 Answers3

1

You need to implement a custom pipe that leverage the reverse method of JavaScript array:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'reverse' })

export class ReversePipe implements PipeTransform {
  transform(value) {
    return value.slice().reverse();
  }
}

You can use it like that:

<li *ngFor="let i of j | reverse">
    {{i}}
</li>

Don't forget to add the pipe in the pipes attribute of your component.

onurkadi
  • 31
  • 2
0

You can do the following

<div *ngFor="let i of j.slice().reverse()">
    {{i}}
</div>
callback
  • 3,981
  • 1
  • 31
  • 55
0

'i of j' implies that j is a collection, not a number, so you can't decrease it as such.

Assuming you meant that you want to 'count backwards' you could call reverse() on j in your component or use a pipe as seen user3146157's answer (original https://stackoverflow.com/a/35703364/9169359). But since it sounds like you want to linearly decrease j, which must be a collection, there's a chance you might be able to re-order the contents of j from the start without additional calls.

IF it's neither j or i which you're hoping to decrease and instead it's something else in the component you haven't mentioned, you could call a method between your curly braces that edits that value:

html

<div *ngFor="let i of j">
    {{updateX()}}
</div>

component

...
  j = [1,2,3,4,5]
  x = 12;

  updateX(){
    return this.x -= 1;
  }
...

but you might get some odd results because of Angular's lifecycle hooks which will call update more times than you expect. For example, setting x to 12 in this example results in 5,4,3,2,1 being printed.

crkaz
  • 38
  • 9