问题描述
我正在使用 PrimeNG 开发 Angular 应用程序。我在问是否可以根据属性值有条件地添加 PrimeNG 组件属性。在我的 HTML 页面中,我有这样的东西:
<span [ngClass]="{'isMobileCalendar' : (isMobile2 | async)}">
<p-calendar monthNavigator="true"
yearRange="1990:2060"
yearNavigator="true"
formControlName="date"
[touchUI]="true"
[style]="{'width':'85%'}">
</p-calendar>
</span>
正如我目前所见,我将此属性设置为 true:[touchUI]="true"。我也在我的 Angular 组件中定义了这个 (isMobile2 | async) 变量,并使用 |async 获取。
我需要实现以下行为:
- 如果 (isMobile2 | async) 值为 true --> 设置:[touchUI]="true"
- 如果 (isMobile2 | async) 值为 false --> 设置:[touchUI]="false"
是否可以通过使用 ngIf 并定义两次 p-calendar 组件来内联实现此行为(基于 isMobile2 | async值)?如果它可以内联完成,那就太好了
解决方法
你试过下面吗?
<span [ngClass]="{'isMobileCalendar' : (isMobile2 | async)}">
<p-calendar monthNavigator="true"
yearRange="1990:2060"
yearNavigator="true"
formControlName="date"
[touchUI]="(isMobile2 | async)"
[style]="{'width':'85%'}">
</p-calendar>
</span>
编辑 1: 这个怎么样?
<ng-container *ngIf="{isMobile:(isMobile2 | async)} as pageState">
<span [ngClass]="{'isMobileCalendar' : pageState.isMobile}">
<p-calendar monthNavigator="true"
yearRange="1990:2060"
yearNavigator="true"
formControlName="date"
[touchUI]="pageState.isMobile"
[style]="{'width':'85%'}">
</p-calendar>
</span>
</ng-container>
,
是的,但是由于 observable 的发射是一个布尔值,您需要使用 TemplateRef
来动态发送值并重用它。
<ng-container *ngTemplateOutlet="template; context: {$implicit: (isMobile2 | async)}"></ng-container>
<ng-template #template let-isMobile2>
<!--
`isMobile2` here is local scoped to `ng-template` and refers to the declaration in `let-isMobile2`.
For the record it could take other names as well.
Eg. `let-myCondition` - in this case,the binding would be `[class.isMobileCalendar]="myCondition"` and `[touchUI]="myCondition"`
-->
<span [ngClass]="{'isMobileCalendar' : isMobile2}">
<p-calendar monthNavigator="true"
yearRange="1990:2060"
yearNavigator="true"
formControlName="date"
[touchUI]="isMobile2"
[style]="{'width':'85%'}">
</p-calendar>
</span>
</ng-template>
对于有条件地应用单个类,您还可以尝试以下代替 ngClass
<span [class.isMobileCalendar]="isMobile2">
...
</span>