0

I have an Angular template that is trying to grab a string that is an HTML element, but the string is not being rendered properly.

Angular Html (fyi this is a subitem in a ng-repeat):

<div class="right-column">{{item.map[label]}}</div>

This string is pulled in and essentially will be formatted such as:

"<a href="..." target="_blank"> Click Here </a>"

The result with this templating is the exact string being shown in the DOM (with some html entities substituted in).

The resulting element in the DOM looks like:

<div class="right-column ng-binding">&lt;a href="..." target="_blank"&gt;Click Here&lt;/a&gt;</div>

I did notice that if I edit the HTML in the browser dev tools and replace the html entities (&lt and &gt) with the actual characters < and > that the html element is being rendered correctly.

I have tried using [innerHTML]="item.map[label]" in the templating, which results in nothing being rendered. I have also tried ng-bind-html="item.map[label]" which was giving errors even when using ngSanitize in the controller js file.

I am not sure what else to try for a proper fix. If there is a way I can format the string that is passed in without messing with the angular template, that would be preferred since there are other formats that are passed into the template other than just this tag style.

adam
  • 1
  • 1

1 Answers1

0

I see there's a typo

"<a href="..."> target="_blank"> Click Here </a>"

should be:

"<a href="..." target="_blank"> Click Here </a>"

I think binding to [innerHTML] should work, if it doesn't work you can tell angular that the HTML is safe and you by pass the sanitizing process. You achieve it by creating a pipe that apply DomSanitizer's bypassSecurityTrustHtml on the HTML string. Example slackblitz:

https://stackblitz.com/edit/angular-2baxog

As a reference you read more here Angular HTML binding

HassanMoin
  • 2,024
  • 1
  • 6
  • 16
  • Thanks for the response. I am thinking that creating a pipe to run byPassSecurityTrustHtml might be the only way to make this work properly. I have followed your slackblitz but am struggling on making the actual pipe class. I'm unsure how to bring in the the imports: import { Pipe } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; Neither of these are being recognized. I have tried adding the respective dependencies/dev dependencies but with no luck. – adam Feb 03 '22 at 19:13
  • @adamcole , did you add the pipe in `declarations` present inside `app.module.ts`? Are you saying that `import { Pipe } from '@angular/core';` etc are giving you errors that they are not present in angular/core ? – HassanMoin Feb 03 '22 at 19:53