在字符串Angular的一部分上应用粗体文本 [英] apply bold text on part of string Angular

查看:137
本文介绍了在字符串Angular的一部分上应用粗体文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的文本的一部分加粗.

I would like to make a part of my text bold.

我从特定文件中获得了文本.

I get a text from a specific file.

"INFORMATION": "Here's an example of text",

"INFORMATION": "Here's an example of text",

我希望Here's an为粗体.

"INFORMATION": "<b>Here's an</b> example of text",

"INFORMATION": "<strong>Here's an</strong> example of text"

然后我打印

<span translate>INFORMATION</span>

而不是得到

这是文本的一个示例

我知道

<b>Here's an</b> example of text

<strong>Here's an</strong> example of text

更新

我正在尝试innerHTML

I'm trying innerHTML

<span [innerHTML]="information | translate"></span>

信息是包含文本的变量

但是它忽略了我的html标签,它只打印文本

but it's ignoring my html tags, it's printing only text

推荐答案

我要做的是使用管道将您提供给它的字符串清理干净,并使用正则表达式使其更通用.像这样的stackblitz:

What I would do is a pipe that sanitizes the string you're giving to it, and use a regex to make it more generic. Something like this stackblitz :

https://stackblitz.com/edit/angular-tyz8b1?file=src%2Fapp%2Fapp.component.html

import { Pipe, PipeTransform, Sanitizer, SecurityContext } from '@angular/core';

@Pipe({
  name: 'boldSpan'
})
export class BoldSpanPipe implements PipeTransform {

  constructor(
    private sanitizer: Sanitizer
  ) {}

  transform(value: string, regex): any {
    return this.sanitize(this.replace(value, regex));
  }

  replace(str, regex) {
    return str.replace(new RegExp(`(${regex})`, 'gi'), '<b>$1</b>');
  }

  sanitize(str) {
    return this.sanitizer.sanitize(SecurityContext.HTML, str);
  }
}

这样,变量内容实际上并没有改变,这意味着您的数据保持不变.

This way, the variable content doesn't actually change, meaning your data remains untouched.

这篇关于在字符串Angular的一部分上应用粗体文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆