javascriptangulartypescriptangular6

How to render a hyperlink in a component template in Angular 6?


I have an Angular 6 application where a component is used to display a message on the page. Some of the messages contain hyperlinks embedded in them (in HTML markup). However, when the messages are displayed on the page, they are getting displayed in plain text (hyperlinks are not rendered, but the markup is displayed to the user instead).

You can visit Stackblitz @ https://stackblitz.com/edit/angular-jj5nms for a sample application that I created to explain the issue.

Expected message display:

Click here.

Actual message display:

Click <a href='http://www.google.com'>here</a>


Solution

  • If you want to render HTML, you need to bind to the innerHTML property of an element, for example:

    <p [innerHTML]="message | async"></p>
    

    Where message is your observable from the service.

    Using handlebars to render message is just rendering plain text, binding to innerHTML and using the async will render your html content.