1

I have a name list : names = ['test1', 'test2', 'test3']

I display them in a simple layout with a simple pipe that searches all names including the user input :

<input type="text" [(ngModel)]="query">
<div *ngFor="let n of names | filterBy: query">{{n}}</div>

Next to the name, there is a little cross to delete it from the list.

The problem is that when I delete an item I previously searched for (for instance test2), the filter isn't actualised. Is it possible to to refresh the content returned by the filter after changing the collection ?

  • I would recommend against doing filters as a pipe. Instead, do the filter in your TS logic. –  May 11 '17 at 07:33
  • Isn't that use case the purpose of a pipe ? –  May 11 '17 at 07:47
  • Please review the following: https://angular.io/docs/ts/latest/guide/pipes.html#!#appendix-no-filterpipe-or-orderbypipe-. Bottom line is that filter and sort pipes don't play that well with change detection. –  May 11 '17 at 10:31

1 Answers1

1

Yes, create a copy of the array using slice() after the modification, then Angular will recognize the change and call the pipe again. Angular doesn't check the content of arrays of objects for changes, only object identity.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • The point of using a pipe was to avoid creating a copy of the array ... Is there really no other way ? –  May 11 '17 at 07:18
  • 1
    You can make the pipe impure, then it's called every time change detection is run. This is usually much worse. You can also introduce an artificial additional pipe parameter to a field that is increased every time after the source array was modified. Angular would recognize the parameter change and call the pipe again. – Günter Zöchbauer May 11 '17 at 07:20
  • If it's only a matter of change detection, might as well call the change detector when I call the delete method then ... I really thought there was a clean, simple way to do that –  May 11 '17 at 07:48
  • If you use `OnPush` with an impure pipe might work, you need to be careful for the pipe not being called to often. Perhaps you can also check within the pipe if the content of the array has changed and only then re-run the filter (see also http://stackoverflow.com/questions/42962394/angular-2-how-to-detect-changes-in-an-array-input-property/42962601#42962601) What option works best depends also a lot of the expected maximum size of the array. – Günter Zöchbauer May 11 '17 at 07:52
  • 1
    Finally I used a double pipe : a pure one (for the arrays with a huge size) and an impure one (just for this example where the max size is 9-10). Thanks for your help ! –  May 11 '17 at 12:13