Angular组件属性内能否添加条件判断?info属性需求咨询
Angular组件info属性的条件赋值实现
不用创建全新组件,直接通过两种方式就能实现info属性的条件显示需求:
方法一:模板内直接使用三元表达式
在info属性的插值表达式里加入三元判断,根据条件返回对应文本或空字符串。示例如下:
<footer-price *ngIf="showPriceWithSavings" title="{{ getTitle() }}" price="{{ getPrice(id, shouldShowPrice) }}" info="{{ shouldShowInfo ? 'to pay ' + (getInfo(id, shouldShowPrice).price | currency : 'GBP' : 'symbol' : '1.2-2') : '' }}" discount="You’ve saved <b>{{ getSavePrice(id, shouldShowPrice).savings | currency : 'GBP' : 'symbol' : '1.2-2' }}</b>" [calculated]="true"> </footer-price>
shouldShowInfo是你需要定义的判断变量(比如根据业务状态、数据是否存在等设置),满足条件时显示to pay ...文本,否则返回空字符串。- 如果需要判断
getInfo返回的数据是否有效,可以结合可选链避免空值报错:info="{{ getInfo(id, shouldShowPrice)?.price ? 'to pay ' + (getInfo(id, shouldShowPrice).price | currency : 'GBP' : 'symbol' : '1.2-2') : '' }}"
方法二:将逻辑抽至组件类(推荐复杂场景)
如果判断逻辑较复杂,或者需要复用该逻辑,建议在组件类中定义方法或属性来处理,让模板更简洁:
- 组件类中添加方法(需注入
CurrencyPipe):
import { CurrencyPipe } from '@angular/common'; constructor(private currencyPipe: CurrencyPipe) {} getInfoText(): string { const infoData = this.getInfo(this.id, this.shouldShowPrice); // 这里替换为你的实际判断条件 if (infoData?.price) { return `to pay ${this.currencyPipe.transform(infoData.price, 'GBP', 'symbol', '1.2-2')}`; } return ''; }
- 模板中直接调用该方法:
<footer-price *ngIf="showPriceWithSavings" title="{{ getTitle() }}" price="{{ getPrice(id, shouldShowPrice) }}" info="{{ getInfoText() }}" discount="You’ve saved <b>{{ getSavePrice(id, shouldShowPrice).savings | currency : 'GBP' : 'symbol' : '1.2-2' }}</b>" [calculated]="true"> </footer-price>
两种方法都能实现需求,根据逻辑复杂度选择即可。
内容的提问来源于stack exchange,提问作者rac3b3nn0n
相关产品推荐
相关产品推荐

