Shanu
Shanu

Reputation: 31

How to display content with html tags for reactive forms Angular

Component.html

<form [formGroup]="formName">
  <input formControlName="title">
</form>

Component.ts

this.formName.patchValue({
  title : this.content
})

Sometimes this.content contains html tags like <i>/<b> tags. In that case, the tags are also displaying. How can we achieve that particular text in italics or bold. Example: this.content = Solve ur doubts in (<i>StackOverflow</i>) Expected Output : Solve ur doubts in (StackOverflow)

In general, by passing this.content in [innerHTML] attribute solved the issue. But in my case it's a reactive form and innerHtML can't be used. Can someone suggest what can be done to get the output as Solve ur doubts in (StackOverflow)

Thanks in advance.

Upvotes: 1

Views: 499

Answers (1)

ArgCedric
ArgCedric

Reputation: 52

you can use innerHTML, exemple:

<div [innerHTML]="content"></div>

Be careful, in your patchValues, it is not an equal but a colon

this.formName.patchValue({ title: this.content })

In some cases, you will need to specify that the html is "secure". For example if it comes from an API I advise you to make a pipe to simplify

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

@Pipe({
  name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {
  constructor(private sanitizer: DomSanitizer) {}

  transform(value: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(value);
  }
}

And to use :

<div [innerHTML]="content | safeHtml"></div>

Upvotes: 2

Related Questions