2016-08-28 1 views
1

表示する背景画像を決定するロジックが非常に複雑です。ここで角度2の複雑な論理を決定する[style.background]が動作しない

は、私はそれを達成しようとしてる方法です:

HTML:

<div class="form-control-icon" 
     id="switch-icon" 
     [style.background]="imagePath"> 
    </div> 

component.ts

import { Component } from '@angular/core'; 
    @Component({ 
     selector: 'distance-units', 
     templateUrl: 'app/find-page/distance-units.component.html', 
     styleUrls: ['app/find-page/distance-units.component.css'] 
    }) 
    export class DistanceUnitsComponent { 
     distanceUnit = "kilometers"; 
     isEnabled = false; 
     isDisabled = true; 
     imagePath = 'url("../images/switch-kilometers-disabled.png") center no-repeat'; 

     constructor() { 
      this.imagePath = 'url("../images/switch-kilometers-disabled.png") center no-repeat'; 
     } 

     toggleDistanceUnit() { 
      this.distanceUnit = 
      (this.distanceUnit === "kilometers" ? "miles" : "kilometers"); 
     } 

     disableSelf() { 

     } 

     setImage() { 
      this.imagePath = this.getImage(); 
     } 

     getImage() { 
      if (this.isEnabled) { 
       if (this.distanceUnit === 'kilometers') { 
        return 'url(\'../images/switch-kilometers.png\') center no-repeat' 
       } else { 
        return 'url(\'../images/switch-miles.png\') center no-repeat' 
       } 
      } else { 
       if (this.distanceUnit === 'kilometers') { 
        return 'url(\'../images/switch-kilometers-disabled.png\') center no-repeat' 
       } else { 
        return 'url(\'../images/switch-miles-disabled.png\') center no-repeat' 
       } 
      } 
     } 
    } 

しかし、ウェブページ内の実際の制御には、バックグラウンドを持っていませんウェブページを実行している間のすべてのプロパティ。当初、imagePath変数は、私がバックグラウンドCSSの有効な値であると思ったものに設定されています。

私は、コンソールでこの警告を得るかが、それは背景が設定されないために引き起こすなぜ私は表示されません。

WARNING:消毒危険なスタイル値 URL(」../画像/ switch-kilometers.png ')center no-repeat( http://g.co/ng/security#xssを参照)。

背景のプロパティが表示されない理由は誰にも見えますか?

+0

はあなたがクラスを追加/削除するために、代わりに直接スタイルを変更すると考えられている:あなたが詳細をお知りになりたい場合は、確保にこの章をチェックしてください!はるかに容易に保守することができます(おそらく実装可能です)。 –

答えて

1

私はこれがあなたのために働くべきだと思います。代わりに[style.background]を置くことだけでこれを行う:角2は、あなたがDOMに注入しようとしている値の「恐れ」であるため、

[ngStyle]="{background: imagePath}" 

問題が発生します。

https://angular.io/docs/ts/latest/guide/security.html

関連する問題