角是否具有“计算属性"?像vue.js中的功能? [英] does angular have the "computed property" feature like in vue.js?
本文介绍了角是否具有“计算属性"?像vue.js中的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我首先学习了Vue.js,现在在Angular 4中有一个项目,所以我才学习Angular.我发现除了计算属性"外,其他一切都与Vue没有什么不同.在Vue中,我可以创建一个计算属性,以侦听其他属性的更改并自动运行计算.
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.
例如(在Vue 2中):
For example(in Vue 2):
computed: {
name(){
return this.firstname + ' ' + this.lastname;
}
}
仅当姓氏或名字之一更改时,name属性才会重新计算.如何在Angular 2或4中处理此问题?
The name property will only recalculate when one of firstname or lastname change. How to handle this in Angular 2 or 4 ?
推荐答案
是的,可以.
在TS文件中:
export class MyComponent {
get name() {
return this.firstname + ' ' + this.lastname;
}
}
然后是html中的
<div>{{name}}</div>
这是一个示例:
@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;
}
}
这篇关于角是否具有“计算属性"?像vue.js中的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文