11

I do request to server and get JSON result:

{"result" => "HTML code"}

How to parse HTML code and get table from this response?

I tried to place this code to hidden block on the page:

<div #content>HTML code here from response</div>

What next? How to parse?

4
  • 6
    Use the innerHtml attribute Commented Sep 18, 2019 at 19:37
  • 1
    Possible duplicate of How to render string with html tags in Angular 4+? Commented Sep 18, 2019 at 19:41
  • 3
    Possible duplicate of Angular HTML binding Commented Sep 18, 2019 at 19:47
  • The div you posted expects text not HTML Commented Sep 18, 2019 at 20:07

2 Answers 2

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

@Pipe({name: 'sanitizeHtml'})
export class SafeHtmlPipe implements PipeTransform {
   constructor(private sanitized: DomSanitizer) {
   }
   transform(value: string) {
     return this.sanitized.bypassSecurityTrustHtml(value);
   }
}

Usage:
<div [innerHTML]="content | sanitizeHtml"></div> //Content is what you got from json

We should always santize the content to prevent any malicious activity with DOMSanitizer. So for that We can create a pipe as above and use it anywhere in app.

Sign up to request clarification or add additional context in comments.

2 Comments

Aren't you bypassing the built-in sanitization here?
to sanitize the HTML, in Angular 15: this.sanitized.sanitize(SecurityContext.HTML, value)
11

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 5';
  demo: string = `<div>
 <p>I am Yogesh</p>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
  </div>`
}

app.component.html

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

2 Comments

I would advise caution on using innerHTML as it can create memory leaks
@JosephBriggs can you say what is the alternative so it's a bit more useful? thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.