angular - 避免在绑定中调用函数
问题描述
我知道我应该避免在绑定中调用函数,因为它们在每个更改周期中都会被调用。我有以下问题,我想避免函数调用,但我找不到解决方法。
这只是一个简化的示例,但它应该显示问题:
一些模板.html
<ng-container *ngFor="let control of group.Controls">
<div [ngSwitch]="control.ControlTypeName" >
<input *ngSwitchCase="'int'" type="text" [formControlName]="getFormControlName(control.PropertyName)">
...
</div>
</ng-container>
一些组件.ts
public getFormControlName(propertyName: string) {
return this.someArray.find(x => x.key === propertyName).formControlName;
}
问题是我需要[formControlName]
输入的属性不在我循环的“控制”对象中*ngFor
。该属性位于不同的数组中,我只能通过调用函数来找到它。
有没有办法避免这种情况?
解决方案
为避免这种情况,您应该有一个查找表(哈希表/映射/对象),由key
具有formControlName
as 值的数组元素索引:
一些组件.ts
some_array = [{key: 'a', formControlName: 'b'}, ...];
control_name = this.some_array.reduce(
(obj, el) => ((obj[el.key] = el.formControlName), obj), {});
一些模板.html
<input *ngSwitchCase="'int'" [formControlName]="control_name[control.PropertyName]" type="text">
推荐阅读
- discord.js - 使用 discord.js v12 接收消息时尝试将消息发送到多个通道
- python-3.x - 在我的计算器中修复未解决的参考?
- flutter - Flutter how to layout top to bottom of other layout
- php - PHP PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: 绑定变量数与标记数不匹配
- flutter-web - Flutter Web App 在 localhost 上运行良好,但在服务器上部署时显示空白屏幕
- node.js - 离题和预处理器离题节点
- python-3.x - 在 Python 中同时为多个变量赋值 - 顺序重要吗?
- amazon-sns - 存在消息属性的 SNS 过滤策略不适用于 0 消息属性
- javascript - 材质 UI 第一个选项卡未显示
- microservices - 微服务测试 - 没有信用卡/借记卡