apply bold text on part of string Angular

做~自己de王妃 提交于 2019-12-25 02:44:26

问题


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


回答1:


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.




回答2:


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

<span translate="{{ 'INFORMATION' }}"></span> 


来源:https://stackoverflow.com/questions/55241693/apply-bold-text-on-part-of-string-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!