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):
JavaScript
x
6
1
computed: {
2
name(){
3
return this.firstname + ' ' + this.lastname;
4
}
5
}
6
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:
JavaScript
1
7
1
export class MyComponent {
2
3
get name() {
4
return this.firstname + ' ' + this.lastname;
5
}
6
}
7
and after that in html:
JavaScript
1
2
1
<div>{{name}}</div>
2
here is an example:
JavaScript
1
20
20
1
@Component({
2
selector: 'my-app',
3
template: `{{name}}`,
4
})
5
export class App {
6
i = 0;
7
firstN;
8
secondN;
9
10
constructor() {
11
setInterval(()=> {
12
this.firstN = this.i++;
13
this.secondN = this.i++;
14
}, 2000);
15
}
16
get name() {
17
return this.firstN + ' ' + this.secondN;
18
}
19
}
20