我知道我应该避免在绑定(bind)中调用函数,因为它们在每个更改周期中都会被调用。我有以下问题,我想避免函数调用,但找不到解决方法。
这只是一个简化的例子,但它应该能说明问题:
some-template.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
为值:
一些组件.ts
some_array = [{key: 'a', formControlName: 'b'}, ...];
control_name = this.some_array.reduce(
(obj, el) => ((obj[el.key] = el.formControlName), obj), {});
some-template.html
<input *ngSwitchCase="'int'" [formControlName]="control_name[control.PropertyName]" type="text">
关于angular - 避免绑定(bind)中的函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52516817/