Angular 2复杂逻辑决定[style.background]不起作用

时间:2016-08-28 05:41:29

标签: angular

我有非常复杂的逻辑决定要显示哪个背景图像。

以下是我试图完成它的方式:

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的有效值。

我确实在控制台中收到了此警告,但我不明白为什么会导致背景无法设置:

  

警告:清理不安全的样式值   url(&#39; ../ images / switch -km.png&#39;)中心不重复(参见   http://g.co/ng/security#xss)。

任何人都可以看到为什么背景属性不存在吗?

1 个答案:

答案 0 :(得分:1)

我认为这对你有用。而不是showData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SQLiteDatabase myDb = mDbHelper.getReadableDatabase(); String[] projection = {"_id",TableFoodMacros.FoodMacros.FOOD_NAME}; Cursor c = myDb.query( TableFoodMacros.FoodMacros.TABLE_NAME, projection, null, null, null, null, null, null ); Log.e("TEST3", String.valueOf(c.getCount())); // Call notifyDatasetChanged when the cursor is filled with data to load the list. db_listView_adapter.notifyDatasetChanged(); } }); 只是这样做:

[style.background]

问题出现是因为Angular 2“害怕”你试图注入DOM的值。如果您想了解更多信息,请查看本章有关保护的内容:

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