首页 > 解决方案 > 为什么我不能在 Angular ngFor 循环中设置我的第一个单词的样式?

问题描述

我目前正在尝试在我的 Angular ngFor 循环中设置字符串的第一个单词的样式。不知何故,类得到了应用,但不是我的 CSS 文件中的样式。内联样式也不起作用 - 为什么?

这是我要应用的 CSS:

#page-image-title-table .first-entry-word {
  font-weight: 500;
}

这是我用上面的类将我的第一个单词包装到一个元素中的函数:

formatTableEntry(tableEntry: string): string {
  const tableEntryParts = tableEntry.split(' ');
  const firstWord       = tableEntryParts[0];

  tableEntryParts.shift();

  const restOfString = tableEntryParts.join(' ');

  return `<span class="first-entry-word">${firstWord}</span> ${restOfString}`;
}

这是我的循环的 HTML:

<div id="page-image-title-table">
  <div class="page-image-title-table-row" *ngFor="let tableEntry of tableEntries">
    <span [innerHTML]="formatTableEntry(tableEntry)"></span>
  </div>
</div>

你可以在这里看到我的工作示例:

https://angular-ivy-g7ov5s.stackblitz.io

标签: htmlcssangulartypescript

解决方案


我在这里看到了多个问题。

  1. 将函数绑定到指令[innerHTML]="formatTableEntry(tableEntry)"将导致默认更改检测策略的性能问题。

  2. innerHTML像您尝试的那样使用绑定在 Angular 中并不优雅。

  3. font-weight: 500是默认的权重值。粗体等于 700。

  4. 也许对实际问题并不重要,但 Stackblitz 在 FF 和 Chrome 中似乎不适合我。

解决方案

您可以启动一个快速管道将句子拆分为所需的格式。

拆分管道.ts

@Pipe({
  name: 'split', 
  pure: true
})
export class SplitPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    if (!value) {
      return null;
    }

    return value.reduce((acc, curr) => {
      const [first, ...rest] = curr.split(" ");
      acc.push({ first: first, rest: rest.join(" ") });
      return acc;
    }, []);
  }
}

然后它可以与*ngFor类似于keyvalue管道的指令结合使用。

尝试以下

app.component.ts

@Component({
  selector: "my-app",
  template: `
    <div id="page-image-title-table">
      <div 
        class="page-image-title-table-row" 
        *ngFor="let tableEntry of (tableEntries | split)"
      >
        <span>
          <span class="first-entry-word">{{ tableEntry.first }}</span>
          {{ tableEntry.rest }}
        </span>
      </div>
    </div>
  `,
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  tableEntries = [
    "First element of the array",
    "Second sample element of the array",
    "lorem ipsum dolor sit amet",
    "Quick brown fox jumps over the lazy dog"
  ];
}

app.component.css

#page-image-title-table .first-entry-word {
  font-weight: 700;
}

工作示例:Stackblitz


推荐阅读