I learnt Vue.js first, and now have a project in Angular 4 so I just learnt Angular. I find everything is not that different from Vue except the "Computed Property". In Vue, I can create a computed property that listens to changes of other properties and run calculations automatically.
For example(in Vue 2):
computed: {
name(){
return this.firstname + ' ' + this.lastname;
}
}
The name property will only recalculate when one of firstname or lastname change. How to handle this in Angular 2 or 4 ?
yes, you can.
In TS file:
and after that in html:
here is an example:
While this is already answered but I think this is not very good answer and users should not use getters as computed properties in angular. Why you may ask? getter is just sugar syntax for function and it will be compiled to plain function, this means that it will be executed on every change detection check. This is terrible for performance because property is recomputed hundred of times on any change.
Take a look at this example: https://plnkr.co/edit/TQMQFb?p=preview
If you really want to have computed properties you can use state container like mobx
mobx has @computed decorator so getter property will be cached and recalculated only when needed
In some cases using a Pure Pipe might be a reasonable alternative, obviously that comes with some restrictions but it at least avoids the costliness of executing the function on any event.
In your template instead of a full name property you might be able to instead just use
' ' | join:firstname:lastname
. Pretty sad that computed properties still don't exist for angular.I will try to improve upon
Andzej Maciusovic
's hoping to obtain a canonical answer. Indeed VueJS has a feature called computed property that can be quickly shown using an example:Whenever the user changes input value for
a
orb
, bothproduct
andproductFunc
are logging to console. If user changesc
, onlyproductFunc
is called.Coming back to Angular, mobxjs really helps with this issue:
npm install --save mobx-angular mobx
observable
andcomputed
attributes for bound propertiesTS file
Markup
If
a
orb
is changed,AB
is called once andgetAB
several times. Ifc
is changed, onlygetAB
is called. So, this solution is more efficient even when computation must be performed.