Angular 2 treating gradients as unsafe

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

  • Why is linear gradient considered unsafe?
  • Is this intended behaviour or just a bug with the current version of Angular 2.
  • Is there a better way to do this without it being considered unsafe?
  • This does have to be dynamic as I'm building the gradient string programatically. I can't use css classes for this.


    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


    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

  • https://github.com/angular/angular/issues/11158
  • 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

    链接地址: http://www.djcxy.com/p/36214.html

    上一篇: 铿锵建造错误

    下一篇: Angular 2将渐变视为不安全