0

I'm working on an email client application for Gmail. When I load some of the emails, the styles from the email body are affecting the styles of our application as well. Few emails have the hardcoded styles for the paragraph and div tag directly. How to isolate the styles from the external sources and make them applicable only for a particular div and its child elements?

Sample style which is causing the issue:

p, ul, ol {
    font-size: 17px;
    line-height: 24px;
    font-weight: normal;
    margin: 0;
    margin-bottom: 15px;
}

The above code paragraph tag has font size set to 17px. which is getting applied throughout the page wherever we use the paragraph tag.

Code to set the email body to the Div:

<div  [innerHTML]="sanitizedemailBody" style="isolation: isolate;"></div>                        

I know that if we use the iframe we can fix this issue but it adds a lot of work as we need to handle the click for the anchor tags in the iframe and some other application-specific restrictions. Is there any better approach to handle this?


Solution from Adam Spence:

external-html.ts

import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-external-html',
  templateUrl: './external-html.component.html',
  styleUrls: ['./external-html.component.scss'],
  encapsulation: ViewEncapsulation.ShadowDom
})
export class ExternalHtmlComponent implements OnInit {
  @Input('externalContent') externalContent: string;
  constructor() { }
  ngOnInit(): void {
  }

}

external-html.html

<div id="externaHtmlHandler" [innerHTML]="externalContent"></div>

And in the parent component's HTML file added the below line:

<app-external-html [externalContent]="currentMessage"></app-external-html>

1 Answer 1

1

You could try using Shadow Dom view encapsulation: https://angular.io/guide/view-encapsulation on the component where you set the innerHtml. The downside is that you will have to redefine all the required styles in that components style file and it takes a bit of getting used to, also browser support could be an issue for you.

Sign up to request clarification or add additional context in comments.

2 Comments

Spense, Thanks for the solution. It worked perfectly. I created a child component and added the Shadow Dom view encapsulation. Now some styles from the app level styles.scss is overwriting the styles in the child component. Any solution for that?
Be careful you aren't using !important anywhere or ng-deep etc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.