I'm trying to set a gradient on a component dynamically and am getting the following warning:
WARNING: sanitizing unsafe style value linear-gradient(#000,#00f) (see http://g.co/ng/security#xss).
Here's a minimal reproduction:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: '<h1 [style.background]="(\'linear-gradient(#000,#00f)\')">My First Angular 2 App</h1>'
})
export class AppComponent {}
My googling tells me to use bypassSecurityTrustStyle
but I'm not happy doing that until I know
This does have to be dynamic as I'm building the gradient string programatically. I can't use css classes for this.
1) Why is linear gradient considered unsafe?
There are restrictions under which misses your style (specifically brackets)
linear-gradient(#000,#00f)
https://github.com/angular/angular/blob/2.0.0-rc.7/modules/%40angular/platform-browser/src/security/style_sanitizer.ts#L30
As of today (RC.7) the RegExp looks like
/^([-,."'%_!# a-zA-Z0-9]+|(?:(?:matrix|translate|scale|rotate|skew|perspective)(?:X|Y|3d)?|(?:rgb|hsl)a?)\([-0-9.%, a-zA-Z]+\))$/g
2) Is this intended behaviour or just a bug with the current version of Angular 2.
I think it is more the expected behavior than the bug
Related issue on github
3) Is there a better way to do this without it being considered unsafe?
You can work around this limitation via writing CustomDomSanitizer
@NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ],
providers: [ { provide: DomSanitizer, useClass: CustomDomSanitizer } ],
})
export class AppModule { }
See also live Plunker Example
It's fixed in Angular 2.4.4 (https://github.com/angular/angular/blob/master/CHANGELOG.md#244-2017-01-19)
PR: https://github.com/angular/angular/pull/13943/files
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With