Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Angular 2 HTML Binding

Here's my problem, I want to include a button inside an HTML template, that links to an external website. But, when HTML is read, Google Chrome says :

WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).

It seems that the Angular 2's innerHTML attribute doesn't allow 2 recursive HTML bindings.

Here's my code :

<ion-col width-80 innerHtml="{{ slide.content + '<p><button round full (click)=`' 
+ slide.button.url +'`>'+slide.button.text+'</button>' }}"></ion-col>

The (click) attribute is deleted, and only (slide.button.text) is displayed as single text.

Any solution ?

slide is like this :

{
    img: 'img/picture.png',
    content: `sometext`,
    button : {
        url: `http://www.foo.com`,
        text: `Site foo`
    }
}
like image 451
Thomas Dussaut Avatar asked Aug 09 '16 14:08

Thomas Dussaut


Video Answer


1 Answers

NOTE: I don't know ion thing so changed it to HTML control. changed button to a (link) control.

You can use DomSanitizationService as shown below,

working demo : http://plnkr.co/edit/y2BXvIO8egNxJPmM3j43?p=preview

//our root app component
import {Component, Pipe} from '@angular/core'
import {DomSanitizationService} from '@angular/platform-browser';

@Component({
  selector: 'my-app',

  template: `
    <span [innerHTML]="myHTML"></span>
  `,
})

export class AppComponent {
  slide={
    img: 'img/picture.png',
    content: `sometext`,
    button : {
        url: `http://www.foo.com`,
        text: `Site foo`
    }
  };

  dangerousUrl='<p><a href='+`${this.slide.button.url}`+'>'+`${this.slide.button.text}`+'</a></p>';

  constructor(sanitizer: DomSanitizationService) {
       this.myHTML= sanitizer.bypassSecurityTrustHtml(this.dangerousUrl);
  }
}
like image 175
Nikhil Shah Avatar answered Sep 20 '22 05:09

Nikhil Shah