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

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

juansaba Published in 2018-01-13 04:51:10Z

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

So I have this in my template:


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>

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.


Faraz Sarwar
Faraz Sarwar Reply to 2018-01-13 06:07:57Z

You can use DomSanitizer provided by angular. For example

import { DomSanitizer } from "@angular/platform-browser"; myHtml: any = '<p> Some Paragraph </p>'; constructor(private sanitizer: DomSanitizer){ this.myHtml = this.sanitizer.bypassSecurityTrustHtml(this.myHtml); }

This is some basic example of how to make HTML trust able for angular, you can use this approach for your scenario.

You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO