user824624
user824624

Reputation: 8080

InnerHTML in angular 4 is not loaded

i am working on @angular/[email protected],

Here is my component html

<div class="contact" [innerHTML]="template">

here is my component ts code

this.template = '<div> hello world </div>';
console.log(self.template );

when the component ts code is running, the console can print out hello world, but this html is loaded to the component automatically, the on the html page is still empty.

why is that and how to fix?

Upvotes: 1

Views: 2387

Answers (2)

Arun Raj R
Arun Raj R

Reputation: 2317

Update your code to this and try,

self.template = '<div> hello world </div>';

If it is not working or you are still suffering try the following jQuery code(This is not a recommended way in Angular2)

HTML: <div class="contact" id="template">

TS: $('#template').html('<div> hello world </div>');

Upvotes: 0

rawkfist0215
rawkfist0215

Reputation: 1485

Some more context around your code snippet would be helpful. Things like how it's declared in the class, where is this initialization happening, is it exposed as a public member of the class are relevant.

However, my guess is that Angular doesn't trust the HTML as "safe".

For my needs I had to create a pipe to handle binding HTML markup to the template:

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

/**
 * See link for more detail: https://stackoverflow.com/questions/39628007/angular2-innerhtml-binding-remove-style-attribute
 */
@Pipe({
  name: 'safeHtml'
})
export class SafeHtmlPipe implements PipeTransform {

  constructor(private sanitized: DomSanitizer) {}

  transform(value: string, args?: any): SafeHtml {
    if(value) {
      return this.sanitized.bypassSecurityTrustHtml(value);
    } else {
      return 'Undefined HTML';
    }
  }

}

See the Angular docs for Dom Sanitizer or follow the the link to the other SO post in the code comment for more info.

Upvotes: 2

Related Questions