我正在使用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]="真">。我还在Angular组件中定义了这个(isMobile2|async(变量,并使用|async获得。
我需要实现以下行为:
- 如果(isMobile2|async(值为true-->set:[touchUI]="真">
- 如果(isMobile2|async(值为false-->set:[touchUI]="false">
是否可以内联实现此行为,而不是使用ngIf并定义两次p-calendar组件(基于isMobile2|async值的值(?如果它可以在线完成,那将是一个漂亮整洁的
是的,但由于可观察到的发射是布尔值,您需要使用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>
你试过下面的吗?
<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>