A simple example to generate reactive computed property in Angular 5 – 在 Angular 5 中使用计算属性

前言 – Preface

无论是 Vue.js 还是 Knockout.js, 计算属性 (Computed Property / Computed State / Calculated State) 都是一个有用的概念。在一般的情况下,尽可能地减少一个组件中的可变 (mutable)状态 (state),可能在一定程度上降低软件复杂度、代码量和风险性(变量不小心被更改)

No matter Vue.js or Knockout.js other other frameworks, Computed Property (Computed State / Calculated State) is a useful concept. It could help to reduce mutable states of a component, thus benefiting on less complexity and less code.

Angular 有么?好像官方文档都没有说哦?当然有,就是 TypeScript 的 property getter, 也就是 ES5 的 Object.defineProperty 时可以用的 getter 了。

Does Angular have the thing? Seems it’s not shown in their tutorials / API docs. Surely, it’s property getter, complied to ES5 Object.defineProperty getter.

示例

https://plnkr.co/edit/9iR8R7x32eE9ha8bPbJf?p=preview

点击 Rename - 改名 按钮时,我们将动态改变用户的名字(First Name)。发现了么? computedName 自动就更新了。

While clicking Rename - ...  , we change User’s first name. And see? The computedNameis automatically updated.