does angular have the “computed property” feature like in vue.js?

前端 未结 6 1512
我在风中等你
我在风中等你 2020-12-28 12:24

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

6条回答
  •  轮回少年
    2020-12-28 12:33

    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:

     
    

提交回复
热议问题