DEV Community

Cover image for How to disable Angular's build-in sanitization for an URL
Adrian Matei for Codever

Posted on • Updated on • Originally published at codever.dev

How to disable Angular's build-in sanitization for an URL

Project: codever - File: backup-bookmarks-dialog.component.ts

On Codever you can backup your bookmarks and snippets. When backing up you are presented a dialog where you can choose to display the items in browser. For that we use a blob URL we know for sure it is safe.

To not get the unsafe prefix in your generated html I use the DomSanitizer and its method bypassSecurityTrustUrl as shown in the example below:

export class BackupBookmarksDialogComponent implements OnInit {

  backupType: string; // 'bookmarks' | 'snippets';
  blobUrl: any;
  sanitizedBlobUrl: any;
  filename: string;

  constructor(
    private dialogRef: MatDialogRef<BackupBookmarksDialogComponent>,
    private router: Router,
    @Inject(MAT_DIALOG_DATA) data,
    private sanitizer: DomSanitizer
  ) {
    this.sanitizedBlobUrl = 
    this.sanitizer.bypassSecurityTrustUrl(data.blobUrl);
    this.blobUrl = data.blobUrl;
    this.backupType = data.backupType;
    const currentDate = new Date();
    this.filename = `${this.backupType}_${currentDate.toISOString()}.json`;
  }
Enter fullscreen mode Exit fullscreen mode

In the html component the sanitizedBlogUrl is injected in the href attribute of the a html element

  <a [href]="sanitizedBlobUrl" [download]="filename" type="button" class="btn btn-primary btn-sm mr-2" (click)="download()"><i class="fas fa-download"></i> Download
  </a>
Enter fullscreen mode Exit fullscreen mode


Reference -

https://angular.io/api/platform-browser/DomSanitizer

Shared with ❤️ from Codever. Use 👉 copy to mine functionality to add it to your personal snippets collection.

Top comments (2)

Collapse
 
ikatsuba profile image
Igor Katsuba

Sorry, but this article should be titled "How to disable Angular's build-in sanitization".

Calling any of the bypassSecurityTrust... APIs disables Angular's built-in sanitization for the value passed in.

Collapse
 
ama profile image
Adrian Matei

Thanks for the tip, it makes sense