2

See https://plnkr.co/edit/7K03F7Orscz0PZdeanNK

export class Filter implements PipeTransform {
    public transform(value: any, args: any[] = []): any {
        return value.filter(() => true); 
        // return value;
    }
}

I'm trying to write a pipe that filters an array. The problem is when I filter the array, the filter function returns a new array and then I get an Expression X changed after it's checked error. I don't get this error only if I mutate the array in place, but this is not what I want to do. Is there anyway of transforming input values using a pipe and not get this error?

jz87
  • 9,199
  • 10
  • 37
  • 42
  • In case you didn't know, this error is only thrown in developer mode. I've had a similiar issue when returning the width of an element that was changed because of a scrollbar and I solved it by returning a style object instead. If you always return the same object and only change the attributes of it, you should be able to solve this error, though I don't know if that is possible here. – Bifrost Feb 09 '16 at 07:56
  • Yeah I'm aware of the developer mode thing. In this case I'm trying to filter a list, so returning the original array won't work. – jz87 Feb 09 '16 at 09:08
  • If you assign the return value of the filtered list to an object and always return that object, it should work. – Bifrost Feb 09 '16 at 13:54
  • but I'm piping this to a ngFor expression, how will the ngFor handle a non-array object? – jz87 Feb 10 '16 at 02:56
  • Possible duplicate of [Expression \_\_\_ has changed after it was checked](http://stackoverflow.com/questions/34364880/expression-has-changed-after-it-was-checked) – drew moore Feb 13 '16 at 03:45

1 Answers1

1

Cache the result and return the cached result while the passed array or filter arguments didn't change.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567