有没有办法有条件地将属性-值对添加到 Angular2+ 中的元素声明中?



>我正在尝试创建一个包装器模板,该模板将包含基于特定条件的某些属性值对。附加属性-值对将是我能想到的最优雅的解决方案......

<ng-template #wrapper let-size="size">
    <custom-component {if size === 'XL', [xlInput]="someVal"}
                      {if size === 'L', [lInput]="otherVal"}
                      {if size === 'M', class="medium"}
                      etc... >
    </custom-component>
</ng-template>

类似于上面的伪代码。

我已经探索了使用 [attr.directive-name]="condition ? someVal : null" 方法有条件地应用指令,但这对于处理我的所有用例来说并不可靠。

为了获得更多背景,我正在使用primeNG的p-table。我的包装器模板是根据输入条件生成特定类型的表(即条件 1 创建一个可选择行的表,条件 2 创建一个不可选择的表,等等(。

我希望有一些类似于下面的伪代码的解决方案。

<ng-template #table let-tableType="tableType"
    <p-table class="myTable" dataKey="var1" [columns]="var2" [value]="var3"
             {if tableType === 'selectable': [(selection)]="var4"}
             {if tableType === 'selectable': (onRowSelect)="someFunc()"}
             {if tableType === 'selectable': (onRowUnselect)="someOtherFunc()"}
             {if tableType === 'selectable': (onHeaderCheckboxToggle)="anotherFunc()"}>
        <ng-content></ng-content>
    </p-table>
</ng-template>

您可以尝试为您的用例制作几个不同的组件,如果差异很大的话。并使用*ngIf*ngSwitch结构指令来选择要使用的正确案例。不要对它们全部使用一个组件,如果您有很多用例,它会变得巨大且失控。

最新更新