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 ?
Advertisement
Answer
yes, you can.
In TS file:
export class MyComponent {
get name() {
return this.firstname + ' ' + this.lastname;
}
}
and after that in html:
<div>{{name}}</div>
here is an example:
@Component({
selector: 'my-app',
template: `{{name}}`,
})
export class App {
i = 0;
firstN;
secondN;
constructor() {
setInterval(()=> {
this.firstN = this.i++;
this.secondN = this.i++;
}, 2000);
}
get name() {
return this.firstN + ' ' + this.secondN;
}
}