apply bold text on part of string Angular

2019-08-20 01:34发布

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",

I would want that Here's an to be bold.

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

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

Then I print it

<span translate>INFORMATION</span>

Instead of getting

Here's an example of text

I get

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

or

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

UPDATE

I'm trying innerHTML

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

Information is variable containing text

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

2条回答
够拽才男人
2楼-- · 2019-08-20 02:29

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.

查看更多
We Are One
3楼-- · 2019-08-20 02:29

You can do this with angular-translate 2.0 if you have it.

<span translate="{{ 'INFORMATION' }}"></span> 
查看更多
登录 后发表回答