Insert HTML into string

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?

1 answer

  • answered 2018-03-13 21:36 Nikolay Zatonatskiy

    Hey guys i don't know why you down vote my answer, but 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