Aternos24
Aternos24

Reputation: 29

Angular html-sanitizing blocking the html code by innerhtml

how can I innerHTML this string ( "<img [src]="img(table[0][0])">" )

it gets blocked by html sanitizing. Also tried to use domsanitizer but it gets rid of src part in img tag. Can anyone please tell me a way to do it? It's impossible that i need to write all that code by hand while i can use for loops.

html: '<div [innerHTML] = "str">'

typescript:

table: string[][] = [
["b0", "b1", "b2", "b3", "b4", "b2", "b1", "b0"],
["b5", "b5", "b5", "b5", "b5", "b5", "b5", "b5"],
["", "", "", "", "", "", "", ""],
["", "", "", "", "", "", "", ""],
["", "", "", "", "", "", "", ""],
["", "", "", "", "", "", "", ""],
["w5", "w5", "w5", "w5", "w5", "w5", "w5", "w5"],
["w0", "w1", "w2", "w3", "w4", "w2", "w1", "w0"]
];
str = "<img [src] = 'img(table[0][0])' (onClick) = 'click(0,0)'>";
img(str: string)
{
     if(str == "") return empty.png;
     return str+".png";
}

Upvotes: 0

Views: 1780

Answers (1)

Daniel V&#225;gner
Daniel V&#225;gner

Reputation: 846

Try to create your own sanitize method in component or even in service if you need to share the logic for sanitize 'getSanitizedHtml'. So the src part will not be removed. And after that you can call 'getSanitizedHtml' for example in ngOnInit.

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

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
  htmlString: SafeHtml;
  table: string[][] // only example of table, dunno how it looks like inside your code

  constructor(private sanitizer: DomSanitizer) { }

  ngOnInit() {
    this.htmlString = this.getSanitizedHtml(this.table[0][0]);
  }

  getSanitizedHtml(imageSrc: string): SafeHtml {
    const html = `<img src="${imageSrc}">`;
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

and call it inside HTML

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

Upvotes: 2

Related Questions