0

I'm trying to create an angular2 method that returns a string representing a html page:

returnAsHtml(myField : MyFieldModel) {

  let html;

  ...

  html += `<tr>
    <td class="text-center">${myField.id}</td>
    <td class="text-center">${myField.name}</td>
    <td class="text-center">${myField.description}</td>
  </tr>`;

  ...

  return html;
}

But the "description" field is a string came from a textarea input filled by user. So we may have line breaks on it. When I print the "html" variable, the line breaks is ignored.

I tried to do something like this:

html += `<td style="white-space: pre-wrap" [innerHTML]='myField.description'></td>`;

But when I do that, the "html" variable just add it as a string, i.e. do not process the innerHTML before add the result on the string.

I also tried:

html += `<td><span style="white-space: pre-wrap">${this.sanitizer.bypassSecurityTrustHtml(myField.description)}</span></td>`;

But I got printed

SafeValue must use [property]=binding

on the html variable;

How can I use innerHTML inside a template literal, or how can I add a variable as html inside a template literal?

aseolin
  • 1,184
  • 3
  • 17
  • 35
  • Good read: https://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background – robert Oct 13 '21 at 19:19

1 Answers1

0

I got it by doing this:

 html += `<td><span style="white-space: pre-wrap">${ this.formatBreakLines(myField.description)}</span></td>`;

 formatBreakLines(field: string) {
    return this.sanitizer.sanitize(SecurityContext.HTML, this.sanitizer.bypassSecurityTrustHtml(field));
}
aseolin
  • 1,184
  • 3
  • 17
  • 35