Aleksandr Belkin Aleksandr Belkin - 3 months ago 38
AngularJS Question

Angular2 raw html custom attribute

I want to insert Raw HTML I get from the server, that has custom attributes in some tags. Angular2 strips out the unknown attributes I need to preserve. I am also very open to alternative ways.

Currently angular2 is embedded into the non-angular page (can't change that), and jQuery selects tags based no their custom attributes so i need to preserve them

import {Component} from '@angular/core'

@Component({
selector: 'my-app',
template: `<div [innerHTML]="rawHtml">[custom] attribute not present</div>`,
})
export class App {
rawHtml = '<span class="class" custom="custom">Text</span>';
}


http://plnkr.co/edit/sKVHUubK0ofUfmSdR5gO?p=preview

Just FYI, I have tried attr.custom, [attr.custom], [custom] without success

Answer

You can use DomSanitizationService to do that

import { DomSanitizationService } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div [innerHTML]="rawHtml"></div>
  `,
  directives: []
})
export class App {
  private _rawHtml: string = '<span class="class" custom="custom">Text</span>';

  public get rawHtml() {
     return this._sanitizer.bypassSecurityTrustHtml(this._rawHtml);
  }

  constructor(private _sanitizer: DomSanitizationService) { }
}

Updated Plunker

Comments