Home Angular 2 - How to bind string containing HTML selectively (a few allowed tags)
Reply: 0

Angular 2 - How to bind string containing HTML selectively (a few allowed tags)

user2242
1#
user2242 Published in April 24, 2018, 8:30 am

I'm implementing some simple search and highlight in my app.

So I have this in my template:

<span>{{myContent}}</span>

And this myContent variable may originally contain data like this (not safe to just put as HTML):

:param: (b (r :a:sync memo :o :idf:3.09 kg;/g/1<>11bwnh :score:0.3

And what I want to do is to provide search and highlight functionality, so my first thought was to use regexp replace and transform my content into something like this (assume search for memo):

:param: (b (r :a:sync <span style='background-color: yellow'>memo</span> :o :idf:3.09 kg;/g/1<>11bwnh :score:0.3

But then I'm having the problem of how to get it rendered safely.

I've seen other questions about binding strings that contain HTML into angular templates, but the most updated one talks about using [innerHTML] and you need to trust the entire HTML.

Is there a way to tell Angular to only trust a specific set of tags?

Alternative what I thought about was to split the results of the search into chunks like this:

chunks = searchAndHighlight(myContent);
// chunks would be:
// [
//  {content: ':param: (b (r :a:sync ', html: false},
//  {content: '<span style='background-color: yellow'>memo</span>', html: true},
//  {content: ' :o :idf:3.09 kg;/g/1<>11bwnh :score:0.3', html: false},
// ]

And then in my template use something like:

<span *ngFor="let chunk of chunks">
  <span *ngIf="chunk.html" [innerHTML]="chunk.content"></span>
  <span *ngIf="!chunk.html">{{chunk.content}}</span>
</span>

But I'm afraid this may kill the performance of my app. My app actually shows a huge tree of data where I'm performing search on each of the nodes, so there are hundred of copies of this Node component, and each of them renders one piece of data (possibly highlighted with search results).

Hope I described the problem well and didn't overwhelm anybody.

Thanks!

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.30428 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO