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 Vu
I'd like to add one more option (TypeScript 4) because the mentioned ways do not 100% meet all needs. It is not reactive but still good enough. The idea is to explicitly declare a function that detects changes and a function that computes property value.
export class ComputedProperty {
private readonly _changes: (previous: TInputs) => TInputs;
private readonly _result: (current: TInputs) => TResult;
private _cache: TResult;
private _inputs: TInputs;
constructor(changes: (previous: TInputs) => TInputs, result: (current: TInputs) => TResult) {
this._changes = changes;
this._result = result;
}
public get value(): TResult {
const inputs = this._changes(this._inputs);
if (inputs !== this._inputs) {
this._inputs = inputs;
this._cache = this._result(this._inputs);
}
return this._cache;
}
}
Declare:
// readonly property
this.computed = new ComputedProperty<[number], number>(
(previous) => {
return previous?.[0] === this.otherNumber ? previous : [this.otherNumber];
},
(current) => {
return current[0] + 1;
}
);
Use: