0

I have the body of an email stored in a javascript/typescript string (message.body). The content of that string is an html code like this:

<div dir="ltr">test mail</div>

I'm using angular bootstrap and I tried this code:

javascript/typescript code:

ShowMessage(message: MailMsg) {

    const modalRef = this.modalService.open(MailModal, { centered: true });
    modalRef.componentInstance.msg = message;
    modalRef.componentInstance.body = $(message.body);

} 

html code:

<div class="bodyMsg">
    <div type="text/html">{{body}}</div>
</div>

I'm getting this output: [object Object]

How can I propperly display the content of that initial message.body string?

Thanks

JFBravo
  • 45
  • 1
  • 6
  • 1
    console log `message.body` in the `showMessage` method, you'll probably spot the problem. –  Aug 11 '20 at 11:51
  • @MikeS. console.log(message.body) outputs this or similar: ```
    test mail
    ```
    – JFBravo Aug 11 '20 at 12:08
  • `or similiar`? Can you provide a screenshot? It is supposedly still an object and not a string so that can't be right. –  Aug 11 '20 at 12:11
  • with 'similar' i mean that it is always a html code in a string format. The output is never a formatted object. BTW, i founded other solution. I post it bellow. – JFBravo Aug 11 '20 at 13:52

3 Answers3

3

Inject the string directly into the innerHTML prop of the component :

<div class="bodyMsg">
    <div [innerHTML]="body | safeHtml"></div>
</div>

but beware of XSS injection :)

cyberbobjr
  • 239
  • 2
  • 6
2

First of all, we need a DomSanitizer instance in the class, so we declare it in the constructor: constructor(private sanitizer: DomSanitizer)

And this is the code for converting the string to a SafeHtml object, that we can import to our html code:

const parser = new DOMParser();
const document = parser.parseFromString(mensaje.cuerpo, 'text/html');
modalRef.componentInstance.body = this.sanitizer.bypassSecurityTrustHtml(document.body.outerHTML);

The last thing missing is to tell out HTML that this code is not malicious and it's safe to display it with the [innerHTML] tag:

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

Working!

JFBravo
  • 45
  • 1
  • 6
0

We can use "pre" tag in angular to render the HTML content as they were.

  <pre>{{ comments }}</pre>
RameshD
  • 912
  • 7
  • 6