角度2中的样式绑定backgrounImage抛出错误

Ali*_*ade 3 angular

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

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

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

Ank*_*ngh 5

[]符号期望expressions,它试图评估url('kgfdgf'),因此你的错误.


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


更新:

这是消毒css的副作用.请参阅github问题以及.

解决方法: 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

用法: <div [style.transform]="'rotate(7deg)' | safe"> asdf </div>


替代方案: PLUNKER

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