![](/img/trans.png)
[英]Use ngFor scoped variable as variable in ngClass for className
[英]ngClass directive to use with ngFor
我有一些列表元素,我使用 *ngFor 指令渲染它们。 但是,根据规范,列表项文本的某些部分应为粗体。 我试图用 [ngClass]="'strong'" 来做到这一点,当 strong 是我需要在文本上添加一些部分的 css 类时。 当我运行应用程序时,结果是整个文本变成粗体。 下面是屏幕截图,以便您更好地理解。
要求是仅使美元部分加粗。 我是角度开发的新手。 任何帮助将不胜感激。
<ul>
<li *ngFor="let text of income; let i = index" [ngClass]="'strong'">{{text.text}}</li>
</ul>
income = [
{text:'Your Annual Income:* $1,316,422'},
{text:'Your Monthly Income: $109,702'}
];
尝试使用此代码:
<ul>
<li *ngFor="let text of income">
{{ text.split(':')[0] }}: <span class="strong">{{ text.split(':')[1] }}</span>
</li>
</ul>
只要你确定它只是关于第一个字母,你就不需要 Angular。 甚至 JavaScript 也不行。 有一个纯 CSS 解决方案。
.first-letter-bold::first-letter { font-weight: 900; font-size: 110%; }
<ul> <li class="first-letter-bold">$1,316,422</li> <li class="first-letter-bold">$1,316,422</li> </ul>
这是因为 {{text.text}} 包含全文。 你必须像这样拆分“li”
<ul>
<li *ngFor="let income of incomes; let i = index" [ngClass]="'strong'">{{income.text}}{{income.value</li>
</ul>
incomes = [
{text:'Your Annual Income:*',
value: '$1,316,422'},
{text:'Your Monthly Income:'
value: '$109,702'}
];
正如其他答案所确定的那样,您需要拆分文本。 我对此的偏好是在界面中创建对收入文本的不同部分进行建模的界面。
export interface Income {
amount: string;
currencySymbol: string;
text: string;
}
在您的组件或服务中(在重用界面时只要有意义),您可以将文本映射到界面。 这就是复杂性所在。 为简单起见,我将展示在组件中使用它的版本。 实际上,您会在服务中这样做以实现可重用性。
incomes: Income[];
ngOnInit() {
this.service.getIncomeTexts().subscribe((texts: string[]) => {
this.incomes = texts.map(x => this.mapTextToIncome(x));
});
}
private mapTextToIncome(text: string): Income {
// this regex will match a string that ends with a dollar symbol
// followed by numbers or commas
// You could extend the possible currency symbols if required
const parts: string[] = /^(.+)(\$)([\d+,]+)$/.exec(text);
return {
amount: parts[3],
currencySymbol: parts[2],
text: parts[1]
};
}
然后在你的 HTML 中使用它变得微不足道:
<ul *ngIf="incomes">
<li *ngFor="let income of incomes">
<span>{{income.text}}</span>
<span class="strong">{{income.currencySymbol}}</span>
<span>{{income.amount}}</span>
</li>
</ul>
在我的示例中,我将数量作为字符串保留,但您可能想要解析它并将其视为数字,以便您可以根据需要应用自己的格式。
演示: https : //stackblitz.com/edit/angular-do6joa
正则表达式演示: https : //regex101.com/r/e4nLLO/2
当然,正确的答案是您的 API 应该以更好的格式返回数据:)
我只修改了您提供的模板部分。
考虑到后端的数据,并假设文本会像您给出的那样,解决方案如下..
使用[innerHTML]属性,您可以逐步拆分字符串,当您到达$
部分时,只需提供 class <b> </b>
例如,
您可以按部分拆分文本部分,例如'<b>'+ text.text.split(' ')[3][0] + '</b>'
。
通过这种方式,您可以仅将$
设为粗体,并且保留文本原样。
<ul>
<li *ngFor="let text of income; let i = index">
<div [innerHTML]="text.text.split(' ')[3][0] ? text.text.split(' ')[0] + ' ' + text.text.split(' ')[1]+ ' ' + text.text.split(' ')[2] + ' ' + '<strong>'+ text.text.split(' ')[3][0] + '</strong>' + ' ' + text.text.split(' ')[3].substring(1) : text.text"></div>
</li>
</ul>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.