Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  122] [ 6]  / answers: 1 / hits: 42666  / 7 Years ago, sun, april 30, 2017, 12:00:00

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 ?


More From » angular

 Answers
34

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;
}
}

[#57954] Thursday, April 27, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hallie

Total Points: 503
Total Questions: 114
Total Answers: 103

Location: Iraq
Member since Fri, Jun 5, 2020
4 Years ago
;