[Angular] Use Angular style sanitization to mark dynamic styles as trusted values

Angular has a very robust security model. Dynamically inserted html, style or url values into the DOM open up possibilities for attackers to compromise your site. Thus Angular treats all values as untrusted by default. In this lesson we learn how to “sanitize” values where we are sure they are trustful.

import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'sanitized-component',
  template: `
    <div [style]="getStyle()">
    </div>
  `
})
export class SanitizedComponent {

  constructor(private sanitizer: DomSanitizer) {}
  getStyle() {
    const gravatarUrl = 'https://cdn1.lelynx.fr/wp-content/uploads/2016/02/chat-pleure-1-150x150.jpg';
    const style = `background-image: url(${gravatarUrl}); 150px; height:150px; border:1px solid black;`;
    return this.sanitizer.bypassSecurityTrustStyle(style);
  }
}
原文地址:https://www.cnblogs.com/Answer1215/p/7365549.html