0

I want to create a Terms and Conditions component in Angular which will be retrieved from a DB. The T&C will include html and user data (user's company). The reason I include html in T&C because I want to be variable and I will change the text as well as the layout in the future.

If I have the following T&C:

<p>The company USERCOMPANY will have the responsibility to accept the T&C</p>

*where the USERCOMPANY will be replaced by user's company

What solution is in Angular and HTML so that it will render my html tags (in thus case p tags) but without rendering the user input in case he adds something like: <strong>My Company</strong> or js script?

1
  • That's not really the purpose of Angular, you should rather store the T&C only, and no HTML/CSS. Commented Aug 10, 2018 at 12:57

1 Answer 1

1

If you have both stored seperately you can escape the value in USERCOMPANY using (quick and dirty):

USERCOMPANYstring.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");

Include your escaped usercompany string into your other html code using some kind of replacement and then put that in your html using a safe pipe: <p [innerHTML]="yourVariable | safe: html"></p>

Safe Pipe:

import { Pipe, PipeTransform } from "@angular/core";
import {
  DomSanitizer,
  SafeHtml,
  SafeStyle,
  SafeScript,
  SafeUrl,
  SafeResourceUrl
} from "@angular/platform-browser";

@Pipe({
  name: "safe"
})
export class SafePipe implements PipeTransform {
  constructor(protected sanitizer: DomSanitizer) {}

  public transform(
    value: any,
    type: string
  ): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
      case "html":
        return this.sanitizer.bypassSecurityTrustHtml(value);
      case "style":
        return this.sanitizer.bypassSecurityTrustStyle(value);
      case "script":
        return this.sanitizer.bypassSecurityTrustScript(value);
      case "url":
        return this.sanitizer.bypassSecurityTrustUrl(value);
      case "resourceUrl":
        return this.sanitizer.bypassSecurityTrustResourceUrl(value);
      default:
        throw new Error(`Invalid safe type specified: ${type}`);
    }
  }
}

This will sanitize your input coming from the database and the escaped characters (i.e. USERCOMPANY) shouldn't appear as html, but the rest would be normal html and trusted by Angular since you sanitized it.

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

Comments

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.