我想在检测到 # 或 @ 时在某些文本周围添加一个跨度,这样我就可以更改颜色,使其看起来像 Twitter 中的用户名和主题标签。我的代码如下所示:
TS 文件:
ngOnInit(): void {
this.glyphService.getAllGlyphs().subscribe(
result => {
this.items = result;
// sort by rune id so list is newest to oldest
this.items.sort((a, b) => Number(b.rune) - Number(a.rune));
for (let i = 0; i < this.items.length; i++) {
this.items[i].glyph_content = this.replaceIt(this.items[i].glyph_content);
console.log(this.items[i])
}
console.log(this.items)
}
);
}
replaceIt = (str: string) => {
const regex = /\B([\#\@][a-zA-Z]+\b)(?!;)/g;
const subst = `<span style="color:blue">$1</span>`;
const result = str.replace(regex, subst);
return result;
}
HTML 文件:
<ion-card *ngFor="let item of items" >
<ion-card-header>
<ion-card-title>@{{item.username}}</ion-card-title>
<ion-card-subtitle>{{item.glyph_date}}</ion-card-subtitle>
</ion-card-header>
<ion-card-content>
{{item.glyph_content}}
</ion-card-content>
</ion-card>
我成功地按照我想要的方式替换了文本,但是它只是作为文本而不是实际标签结束,看起来像这样:
test <span style="color:blue">@hey</span> <span style="color:blue">@uh</span> wow <span style="color:blue">#ah</span> words <span style="color:blue">#oh</span>
有没有办法让我更改我的代码,以便我实际上可以像我想要的那样将目标文本动态地包装在真实的跨度中?是否可以在这里以某种创造性的方式使用 *ngIf ?
我们需要使用
DomSanitizer
和 [innerHtml]
才能实现此目的。
在你的 component.ts 文件中:
// TS File
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';
export class YourComponent implements OnInit {
items: any[] = [];
constructor(
private glyphService: GlyphService,
private sanitizer: DomSanitizer
) {}
ngOnInit(): void {
this.glyphService.getAllGlyphs().subscribe(
result => {
this.items = result;
// sort by rune id so list is newest to oldest
this.items.sort((a, b) => Number(b.rune) - Number(a.rune));
for (let i = 0; i < this.items.length; i++) {
this.items[i].glyph_content_html = this.sanitizer.bypassSecurityTrustHtml(
this.replaceIt(this.items[i].glyph_content)
);
}
console.log(this.items);
}
);
}
replaceIt = (str: string): string => {
const regex = /\B([\#\@][a-zA-Z]+\b)(?!;)/g;
const subst = `<span style="color:blue">$1</span>`;
const result = str.replace(regex, subst);
return result;
}
}
在您的 HTML 中:
<ion-card *ngFor="let item of items">
<ion-card-header>
<ion-card-title>@{{item.username}}</ion-card-title>
<ion-card-subtitle>{{item.glyph_date}}</ion-card-subtitle>
</ion-card-header>
<ion-card-content [innerHTML]="item.glyph_content_html">
</ion-card-content>
</ion-card>