0

Using Angular 5 and Firebase, I have created a review website that allows users to create reviews on the CreateComponent and read them on the ReviewComponent. I'd like the body of the review to be able to contain HTML for links or images.

The ReviewComponent pulls the body of the review with:

<p style="margin-bottom: 2rem; white-space: pre-wrap;">{{review.body}}</p>

I am using pre-wrap to maintain the body's line breaks.

An example input from the CreateComponent would be:

I already can’t wait to see <a href="http://www.ign.com/articles/2017/11/30/marvels-the-avengers-infinity-war-trailer-breakdown"> what comes next.</a>

When I inspect the output of the body I see this:

<p _ngcontent-c1 style="margin-bottom: 2rem; white-space: pre-wrap;">I already can’t wait to see &lt;a href="http://www.ign.com/articles/2017/11/30/marvels-the-avengers-infinity-war-trailer-breakdown"&gt;what comes next.&lt;/a&gt;</p>.

How can I change the HTML to enable the string to work correctly with links and images?

KENdi
  • 7,576
  • 2
  • 16
  • 31
cfoster5
  • 1,696
  • 5
  • 28
  • 42

2 Answers2

0

Here is solutions for your issue:

https://plnkr.co/edit/VHvVpvnTeoGWsA0d3eex?p=preview

Here is code:

//our root app component
import {Component, NgModule, VERSION, Pipe, PipeTransform, ChangeDetectorRef } from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
    <div [outerHTML]='selectedValue | html'></div>
  `,
})
export class App {
  selectedValue: string = 'I already can’t wait to see <a href="https://www.ign.com/articles/2017/11/30/marvels-the-avengers-infinity-war-trailer-breakdown"> what comes next.</a>';
  constructor(private cd: ChangeDetectorRef) {
  }
}


@Pipe({
  name: 'html'
})
export class HtmlPipe implements PipeTransform {

  transform(value: string) {
      return `<div>${value}</div>`;
  }

}

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App, HtmlPipe ],
  bootstrap: [ App ]
})
export class AppModule {}

You could write pipe for this application, like in this article:

How to allow html in return of angular2 pipe?

miken32
  • 42,008
  • 16
  • 111
  • 154
0

Binding review.body to [innerHTML] corrected this.

<p style="margin-bottom: 2rem; white-space: pre-wrap;">{{review.body}}</p>

is now

<p style="margin-bottom: 2rem; white-space: pre-wrap;" [innerHTML]="review.body"></p>
cfoster5
  • 1,696
  • 5
  • 28
  • 42