The pure property

We can add a property to our @Pipe decorator, pure, like so:

@Pipe({ name : 'myPipe', pure : false })
export class MyPipe implements PipeTransform {
transform(value: any, ...args: any[]) {}
}

"Why would we do that in the first place?" you ask. Well, there are situations where this might be necessary. If you have a pipe that works on primitives like so:

{{ "decorate me" |  myPipe }}

We don't have an issue. However, if it looks like this:

{{ object | myPipe }}

We might have a problem. Consider the following code in a component:

export class Component {
object = { name : 'chris', age : 37 }

constructor() {
setTimeout(() => this.object.age = 38 , 3000)
}
}

Imagine that we have the following Pipe implementation to go with it:

@Pipe({ name : 'pipe' })
export class MyPipe implements PipeTransform {
transform(value:any, ...args: any[]) {
return `Person: ${value.name} ${value.age}`
}
}

This would at first be the output:

Chris 37

However, you expect the output to change to Chris 38 after 3 seconds, but it doesn't.  The pipe only looks at whether the reference have changed or not. In this case, it hasn't because the object is still the same, but a property on the object has changed. A way to tell it to react to changes is to specify the pure property, like we did in the beginning. So, we update our Pipe implementation to look like this:

@Pipe({ name : 'pipe', pure: false })
export class MyPipe implements PipeTransform {
transform(value: any, ...args:any[]) {
return `Person: ${value.name} ${value.age}`
}
}

Now, we suddenly see the change happen. A word of caution though. This actually means the transform method is called every time the change detection cycle is being triggered. So, this might actually be damaging for performance. You could try and cache the value if setting the pure property, but you could also try to work with reducers and immutable data to solve this in a better way:

// instead of altering the data like so
this.jedi.side = 'Dark'

// instead do
this.jedi = Object.assign({}, this.jedi, { side : 'Dark' });

The preceding code would change the reference and our Pipe wouldn't kill performance. All in all, it's good to know what the pure property does, but be careful.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset