2016-06-21 155 views
1

我正在使用angular2 rc2和typescript。 我有一个角色2组件,其中颜色是使用属性设置的。Angular 2从组件中设置动态样式(背景图像:线性渐变)

组件内部的颜色被转换为rgba并创建线性渐变,我想将其设置为模板。

import { Component, Input, OnInit } from "@angular/core"; 

@Component({ 
     selector: "horizontalrule", 
     template : `<div class="fadding-ruller-holder"> 
         <hr class="fadding-ruller" [style.background-image]="BackgroundImage"> 
        </div>`, 
}) 

export class HorizontalRule implements OnInit 
{ 
     @Input() color:string; 

     public BackgroundImage:string; 

     constructor(private utils:UtilsService) 
     { 

     } 

     ngOnInit() 
     { 
      //color: #FF0000 

      let rgba:string = this.ConvertHexToRGBA(this.color, 0.7); 

      //rgba: rgba(255,0,0,0.7) 

      this.BackgroundImage = "-webkit-linear-gradient(left, rgba(0, 0, 0, 0)," + rgba + "rgba(0, 0, 0, 0))" 
            + "-o-linear-gradient(left, rgba(0, 0, 0, 0)," + rgba + "rgba(0, 0, 0, 0))" 
            + "linear-gradient(to right, rgba(0, 0, 0, 0)," + rgba + "rgba(0, 0, 0, 0))"; 
     } 

     public ConvertHexToRGBA(hex:string, opacity?:number):string 
     { 
      opacity = opacity || 1; 

      opacity < 0 ? opacity = 0 : opacity = opacity; 
      opacity > 1 ? opacity = 1 : opacity = opacity; 

      hex = hex.replace('#',''); 

      let r = parseInt(hex.substring(0, 2), 16); 
      let g = parseInt(hex.substring(2, 4), 16); 
      let b = parseInt(hex.substring(4, 6), 16); 

      return 'rgba(' + r + ',' + g + ',' + b + ',' + opacity +')'; 

     } 
} 

这是行不通的。有些东西失败了,渐变甚至没有在html中设置。这是做到这一点的正确方法吗?

+0

听起来像http://stackoverflow.com/questions/37076867/in-rc-1-some-styles-cant-be-added-using-binding-syntax/37076868#37076868 –

回答

2
import {DomSanitizationService} from '@angular/platform-browser'; 

class HorizontalRule implements OnInit { 
    transform(style) { 
    return this.sanitizer.bypassSecurityTrustStyle(style); 
    } 

    ngOnInit() { 
     //color: #FF0000 

     let rgba:string = this.transform(this.ConvertHexToRGBA(this.color, 0.7)); 

     //rgba: rgba(255,0,0,0.7) 

     this.BackgroundImage = this.transform("-webkit-linear-gradient(left, rgba(0, 0, 0, 0)," + rgba + "rgba(0, 0, 0, 0))" 
           + "-o-linear-gradient(left, rgba(0, 0, 0, 0)," + rgba + "rgba(0, 0, 0, 0))" 
           + "linear-gradient(to right, rgba(0, 0, 0, 0)," + rgba + "rgba(0, 0, 0, 0))";) 
    } 
} 
+0

我不得不做出一些调整,但这是正确的,我们需要使用DomSanitizationService。如果我只有线性渐变,它的工作原理。如果我添加其他前缀它不起作用... – hsantos

+0

很高兴听到你想出了它:)有些东西默认情况下被列入白名单,其他人需要明确的消毒。 –