angular - 使用模型类的 Angular 绑定中的可伸缩性
问题描述
我是 Angular 的新手,正在寻找一种可销售的模块化方式来填充类中的一组派生变量。
export class Calculator {
constructor(
public x?: number,
public y?: number,
public total?: number,
) {
this.total = this.x + this.y;
}
}
我应该发生的是,Angular 应该知道total
和x
,之间存在依赖关系y
。每当x
或y
更新时,Angular 都应该重新评估total
.
我知道这可以通过写作来完成,
this.calculator.total = this.calculator.x + this.calculator.y
在ngOnInit
控制器或onchange
触发器中。但是,如果我有很多派生变量,它是不可扩展和模块化的。确实,Class 只是打字稿,它不了解 Angular。你能帮我提出替代方案吗?
解决方案
如果对总使用 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();
}
}
现在,只要对象内发生更改,您就可以重新计算多个属性。
推荐阅读
- typescript - 如何修复 OpenLayers 6.6.1 中的 Typescript 错误
- excel - Excel 条件和基于不同列中依赖的逻辑
- pandas - 如何对我的数据框 Pandas 中具有特定条件的行求和?
- python - 如何将具有不同最大值的等高线子图全部映射到相同的颜色条?
- php - 发送数据到 api
- sql-server - 如何将两个模式导出到 Sql Server 中的同一个文件?
- json - 问:如何指定此模式要满足的条件?
- javascript - React:usePrevious 钩子仅在组件中有 1 个状态时才有效。如果有多个状态,如何使其工作?
- python - 熊猫分组但保留原始索引和重复的聚合值
- c# - ASP NET Core Web API 禁用 TLS 1.0 和 TLS 1.1 支持