Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 add dynamic html file into DIV

Tags:

html

angular

I am very new to Angular, I am trying to insert the html file as my string and insert into DIV element

I have my search.component.html called

<div #ID></div>

components.ts

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

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss']
})
export class SearchComponent {
  constructor() {}

  let ServerResponseHtml = '<div><input type="text"/><input type="text"/><span class="btn btn-outline-primary btn-sm" (click)="open(content)">View Document</span></div>';

  document.getElementById("DIV").innerHTML = ServerResponseHtml;
}

I am getting the response from server as complete html markup, Just I need to append into my DOM and display the content, the markup can have inline styles also.

I tried for <div [innerHTML]="ServerResponseHtml"></div> and <div innerHTML="{{ServerResponseHtml}}"></div> but this is not displaying as html it is displayed as text.

like image 664
Umesha D Avatar asked Jan 28 '23 20:01

Umesha D


1 Answers

We need to use the safehtml for displaying the html.

  1. We need to create the Pipe for this. safe-html-pipe.ts
    import {DomSanitizer, SafeHtml} from '@angular/platform-browser';
    import {Pipe, PipeTransform} from '@angular/core';
    
    @Pipe({name: 'safehtml'})
    
    export class SafeHtmlPipe implements PipeTransform {
      constructor(private sanitized: DomSanitizer) {
      }
    
      transform(value): SafeHtml {
        return this.sanitized.bypassSecurityTrustHtml(value);
      }
    }
  1. component.ts We need to import the pipe

import {Component, NgModule, Pipe, PipeTransform} from '@angular/core'

import {BrowserModule} from '@angular/platform-browser'
import { FormsModule } from '@angular/forms';
import { DomSanitizer } from '@angular/platform-browser'
import { SafeHtmlPipe } from './safe-html-pipe';
@Component({
selector: 'app-root',
template: 
    `<div [innerHtml]="safeHtmlContent | safehtml">
 </div>"})`
 
export class AppComponent {
 name:string;
  safeHtmlContent : string;
  constructor() {
    this.name = 'Angular2'
    this.safeHtmlContent  = '<html><head><title>Hello safe</title></head><body><h1>hello world Hello Umesh</h1></body></html>';
  }
}

Hope this helps :).

like image 179
Umesha D Avatar answered Jan 31 '23 19:01

Umesha D