POV
POV

Reputation: 12005

How to parse HTML from response in Angular?

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?

Upvotes: 11

Views: 23121

Answers (2)

Yogesh Waghmare
Yogesh Waghmare

Reputation: 1045

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>

Upvotes: 11

Siddharth Pal
Siddharth Pal

Reputation: 1458

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.

Upvotes: 13

Related Questions