角度2 backgroun中的样式绑定图像抛出错误 [英] style binding in angular 2 backgrounImage throw error

查看:54
本文介绍了角度2 backgroun中的样式绑定图像抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个角度为2的应用程序 这是我的模板:

I'm trying to create a application with angular 2, this is my template :

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

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

i think's angular2 think's url() is a function and throw an error...what is the solution for this problem?

推荐答案

[]表示法期望使用expressions,它会尝试评估url('kgfdgf'),因此会出现错误.

[] notation expects expressions, it tries to evaluate url('kgfdgf'), hence your error.

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

[style.background-color] is a possible binding, [style.background-image] is not ( PLUNKER )

更新:

消毒css的副作用.参见 github问题

Which is a side-effect of sanitizing the css. See github issue and this and this.

解决方法:: PLUNKER

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

Where QuentinFchx mentioned a workaround using pipe

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);
    }
}

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

替代: PLUNKER

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

这篇关于角度2 backgroun中的样式绑定图像抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆