0

In Component.ts file I have a variable textValue = "Hello World!"; and subTextValue = "ll". and in component.html file I try to set particular character of string in "Hello World!" ----> "Hello World!" to bold using the below line of code.

<span>{{textVal.replace(textValue , '<b>' + subTextValue  + '</b>')}}</span>

But, I get output as {{textVal.replace(textValue , '' + subTextValue + '')}}

Can someone help me with this.

3 Answers 3

3

You should use a pipe for this function in innerHTML (for rendering html)

<span [innerHTML]="textVal | markBold:subTextValue"></span>

In the pipe

transform(textVal: string, subTextValue: string): string {
    return textVal.replace(textValue , '<b>' + subTextValue  + '</b>');
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can create a pipe as below:

@Pipe({
  name: 'bold'
})
export class BoldPipe implements PipeTransform {
 transform(textValue: string, subTextValue: string): string {     
     return textValue.replace(new RegExp(`(${subTextValue})`, 'gi'), '<b>$1</b>');
 }
}

and in HTML:

<span [innerHTML]="textValue | bold:subTextValue"></span>

This should give you:

Hello World!

Comments

0

Can you try with below code. This is the easiest way to do.

<span [innerHTML] = "textVal.replace(textValue , '<b>' + subTextValue  + '</b>')"></span>

If you want a more clean way you could create a pipe for that.

In pipe

@Pipe({
  name: 'textBold'
})
export class TextBoldPipe implements PipeTransform {
 transform(textValue: string, subTextValue: string): string {     
     return textValue.replace(subTextValue, '<strong>' + subTextValue + '</strong>');
 }
}

In HTML

<span [innerHTML]="textValue | textBold:subTextValue"></span>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.