html - 为什么我不能在 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>
你可以在这里看到我的工作示例:
解决方案
我在这里看到了多个问题。
将函数绑定到指令
[innerHTML]="formatTableEntry(tableEntry)"
将导致默认更改检测策略的性能问题。innerHTML
像您尝试的那样使用绑定在 Angular 中并不优雅。font-weight: 500
是默认的权重值。粗体等于 700。也许对实际问题并不重要,但 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
推荐阅读
- c++ - wxWidgets CallAfter 唤醒 macOS 上的主 UI 线程?
- python - 如何确定具有重复符号但*没有*“功能相同”集合的集合的所有排列
- python - 从 Python 脚本调用时,如何获取 .exe 文件以识别同一文件夹中的文件?
- reactjs - Reactjs Antd 库和谷歌地图 Places
- c++ - 如何在 makefile 中包含字符串 fstream 和 iostream 库
- css - 未定义的混合
- python - Python Regex 仅用于第一个匹配项并忽略其他匹配项
- python - requirements.txt:以 python 版本为条件
- angular - 自动将前端应用程序的标头附加到外部http请求?
- vb.net - 创建命令以搜索现有用户的 Excel 数据库(在带有 Windows 窗体的 Visual Basic 上使用 OleDb)