与 ngFor 一起使用的 ngClass 指令

ngClass directive to use with ngFor

我有一些列表元素,我正在使用 *ngFor 指令进行渲染。但是,根据规范,列表项文本的某些部分应为粗体。我试图用 [ngClass]="'strong'" 来做到这一点,当强是 css class 我需要在文本上添加一些部分。当我 运行 应用程序时,结果是整个文本都变成了粗体。下面是屏幕截图,以便您更好地理解。

要求仅将美元部分设为粗体。我是 angular 开发的新手。任何帮助将不胜感激。

<ul>
      <li *ngFor="let text of income; let i = index" [ngClass]="'strong'">{{text.text}}</li>
    </ul>
income = [
    {text:'Your Annual Income:* ,316,422'},
    {text:'Your Monthly Income: 9,702'}
  ];

因为{{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: ',316,422'},
  {text:'Your Monthly Income:'
    value: '9,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">,316,422</li>
  <li class="first-letter-bold">,316,422</li>
</ul>

正如其他答案所指出的那样,您需要拆分文本。我对此的偏好是在对收入文本的不同部分建模的界面中创建。

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 应该 return 数据格式更好:)

我只修改了你给的模板部分

考虑到后端的数据,假设文本会像你给的那样,解决方案如下..

使用 [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>

Working Stackblitz