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}); width:150px; height:150px; border:1px solid black;`; return this.sanitizer.bypassSecurityTrustStyle(style); } }