Is there any benefit of using the filter function inside ngFor?

I found several answers here, where people recommend using a line of code similar to this:

<div *ngFor="let x of filter(myArray)">

However, it filter(myArray)starts constantly.

I found that storing 2 arrays like the ones below is much more efficient.

<div *ngFor="let x of filteredArray">

the code

let fullArray = [1,2,3,4,5,6]
let filteredArray = []

onFilterEvent() {
    filteredArray = fullArray.filter(x => /* filtering logic */)
}

The disadvantage here is that I constantly rewrite the contents filteredArray. However, it only works when filtering logic is required, and not constantly.

Is there a reason to use the first method? He still does the same job, but he does it again and again.

+4
source share
2 answers

Angular . :

Angular Angular . filterHeroes sortedHeroes , . , , / .

https://angular.io/guide/pipes#appendix-no-filterpipe-or-orderbypipe

+2

ngFor?

*ngFor, . ChangeDetectionStrategy.OnPush , :

  • ,
  • ,

:

@Component({
  selector: 'my-app',
  template: `
    <button (click)="refilter()">Refilter</button>
    <h3>Filtered array</h3>
    <div *ngFor="let i of filter(array)">{{i}}</div>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class App {
  array = [0,1,2,3,4,5,6,7,8,9];

  constructor(protected cdr: ChangeDetectorRef) {}

  filter(array: Array) {
    console.log('array filtered!');
    return array.filter(i => i < 5);
  }

  refilter() {
    this.cdr.markForCheck();
  }
}

PLNKR: https://plnkr.co/edit/qkkW9U7rDlI6eSYGEUrf?p=info

, , , .

0

Source: https://habr.com/ru/post/1683117/


All Articles