首页 > 解决方案 > 避免在绑定中调用函数

问题描述

我知道我应该避免在绑定中调用函数,因为它们在每个更改周期中都会被调用。我有以下问题,我想避免函数调用,但我找不到解决方法。

这只是一个简化的示例,但它应该显示问题:

一些模板.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。该属性位于不同的数组中,我只能通过调用函数来找到它。

有没有办法避免这种情况?

标签: angular

解决方案


为避免这种情况,您应该有一个查找表(哈希表/映射/对象),由key具有formControlNameas 值的数组元素索引:

一些组件.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">

推荐阅读