首页 > 解决方案 > 使用模型类的 Angular 绑定中的可伸缩性

问题描述

我是 Angular 的新手,正在寻找一种可销售的模块化方式来填充类中的一组派生变量。

export class Calculator {
    constructor(
        public x?: number,
        public y?: number,
        public total?: number,
    ) {
        this.total = this.x + this.y;
    }
}

我应该发生的是,Angular 应该知道totalx,之间存在依赖关系y。每当xy更新时,Angular 都应该重新评估total.

我知道这可以通过写作来完成,

this.calculator.total = this.calculator.x + this.calculator.y

ngOnInit控制器或onchange触发器中。但是,如果我有很多派生变量,它是不可扩展和模块化的。确实,Class 只是打字稿,它不了解 Angular。你能帮我提出替代方案吗?

标签: angulartypescriptdata-bindingbinding

解决方案


如果对总使用 getter 效率不高,您可以将Calculator类更新为类似

export class Calculator {
    constructor(
        private _x?: number,
        private _y?: number,
        public total?: number,
    ) {
        this.total = this.x + this.y;
    }
    private update() {
        this.total = this.x + this.y;
    }
    set x(val) {
        this._x = val;
        this.update();
    }
    set y(val) {
        this._y = val;
        this.update();
    }
}

现在,只要对象内发生更改,您就可以重新计算多个属性。


推荐阅读