【问题标题】:Is there a way to conditionally add attribute-value pairs to an element declaration in Angular2+?有没有办法有条件地将属性值对添加到 Angular2+ 中的元素声明?
【发布时间】:2018-08-06 19:24:10
【问题描述】:

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

<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>

【问题讨论】:

    标签: angular primeng ng-template


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-10
      • 2012-10-09
      • 2018-12-20
      • 2011-11-22
      • 2019-06-21
      • 1970-01-01
      • 2015-04-05
      • 1970-01-01
      相关资源
      最近更新 更多