【问题标题】:style binding in angular 2 backgrounImage throw errorangular 2 backgrounImage 中的样式绑定抛出错误
【发布时间】:2016-05-18 12:56:12
【问题描述】:

我正在尝试使用 angular 2 创建一个应用程序, 这是我的模板:

<div class="cover_user_profile"
       [style.backgroundImage]="model.cover ? url(model.cover) : url('client/img/profile_user/test.png') ">
</div>

我认为 angular2 认为的 url() 是一个函数并抛出错误......这个问题的解决方案是什么?

【问题讨论】:

    标签: angular


    【解决方案1】:

    [] 表示法需要expressions,它试图评估url('kgfdgf'),因此你的错误。


    [style.background-color] 是可能的绑定,[style.background-image] 不是(PLUNKER


    更新:

    这是清理 CSS 的副作用。请参阅github issuethisthis

    解决方法: PLUNKER

    QuentinFchx 提到了使用管道的解决方法

    import {DomSanitizationService} from '@angular/platform-browser';
    @Pipe({name: 'safe'})
    export class SafePipe {
        constructor(sanitizer:DomSanitizationService){
            this.sanitizer = sanitizer;
        }
    
        transform(style) {
            return this.sanitizer.bypassSecurityTrustStyle(style);
        }
    }
    

    用法:&lt;div [style.transform]="'rotate(7deg)' | safe"&gt; asdf &lt;/div&gt;


    替代方案: PLUNKER

     [ngStyle]="{'background-image': 'url(' + (model.cover || 'client/img/profile_user/test.png') + ')'}"
    

    【讨论】:

      【解决方案2】:

      你可以使用这个有效的表达式:

      <div class="cover_user_profile"
         [style.backgroundImage]="model.cover ? 'url(' + model.cover + ')' : 'url(client/img/profile_user/test.png)'">
      </div>
      

      事实上,url 不是一种方法,而是特定于 CSS 的东西,需要出现在最终的字符串中。

      【讨论】:

      • 但是[style.backgroundImage] 什么都不做,即使[style.background-image] 也没有效果,也许不能用[style.attribute] 符号添加图像?
      • 妈妈,我认为您是对的 ;-) 也许是因为破折号... +1 为您的答案!
      • 谢谢! ..... 但是background-color 有效,它可能是一个错误或者只是不支持 angular
      • 我开了一个issue,看看结果如何
      猜你喜欢
      • 2013-02-10
      • 2017-05-27
      • 2017-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多