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

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

juansaba
1#
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: {{myContent}}  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 memo :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: 'memo', html: true}, // {content: ' :o :idf:3.09 kg;/g/1<>11bwnh :score:0.3', html: false}, // ]  And then in my template use something like:  {{chunk.content}}  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!
Faraz Sarwar
2#
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 = '

Some Paragraph

'; 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.
Processed in 0.303119 second(s) , Gzip On .