简体   繁体   中英

Angular Interpolation for HTML a tag element

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM