1

I have one HTML page which I am getting from the third party.

The issue is HTML comes with CSS inside style tag. That CSS is kind of generic where they are adding their own font and own font size on body.

I am using dom sanitizer with bypassSecurityTrustHtml for showing HTML on my application.

this.domSanitizer.bypassSecurityTrustHtml(htmldata);

Now after adding new HTML, my application style is getting affected because of that. How can I avoid this except adding third-party URL in an iframe?

Z. Bagley
  • 8,942
  • 1
  • 40
  • 52
Nitish
  • 651
  • 1
  • 7
  • 14
  • Do you need to keep all their styles? Why not just strip their styles from the html that aren't necessary (like for the body styles), before injecting the html? – Narm May 18 '18 at 18:03
  • What exactly is being overwritten in your app? You can try changing the class names in your app so they don't clash with the 3rd party html. Not much else you can do if they didn't namespace their css well. – Chase DeAnda May 18 '18 at 18:14

1 Answers1

1

You are looking for ViewEncapsulation.Native. You will need to create a custom component that only has the DOM element you are injecting the innerHTML into.

What setting this ViewEncapsulation to Native means is that it creates Shadow DOM, and ensures that it becomes the parent element and all styling and DOM references are contained to itself.

An example on setting ViewEncapsulation to Native. You would provide your DOM and innerHTML inject here:

import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
@Component({
  selector: 'app-my',
  templateUrl: './my.component.html',
   styles: [
    `h1 {
      color: #367;
      font-family: Arial, Helvetica, sans-serif;
      font-size: 250%;
    }
  `],
   encapsulation: ViewEncapsulation.Native
})
export class MyComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}
Z. Bagley
  • 8,942
  • 1
  • 40
  • 52
  • yes this works. but it is not supported in IE 11 also. that is creating issue for me now – Nitish May 22 '18 at 21:04
  • @Nitish 100% browser support for native angular items using es6 polyfills: https://angular.io/guide/browser-support – Z. Bagley May 22 '18 at 21:29
  • thanks will check now but i saw this https://github.com/angular/angular/issues/6531 – Nitish May 22 '18 at 22:10
  • @Nitish It's included nowadays, that issue was resolved almost 2 years ago when it came out of Beta. – Z. Bagley May 22 '18 at 22:45
  • I have enabled all polyfills for IE. all core-js, classlist, core-js/es6/reflect, core-js/es7/reflect, zone.js/dist/zone. but it still issue – Nitish May 23 '18 at 08:13