2016-06-21 6 views
1

私はangular2 rc2とtypescriptを使用しています。 プロパティを使って色を設定する角度2のコンポーネントがあります。角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

あなたがそれを理解してくれたことをうれしく思います:)デフォルトではホワイトリストに登録されているものもあれば、明示的な消毒が必要なものもあります。 –

関連する問題