4

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>

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

2 Answers2

5

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


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


Update:

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

Workaround: PLUNKER

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

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


Alternative: PLUNKER

 [ngStyle]="{'background-image': 'url(' + (model.cover || 'client/img/profile_user/test.png') + ')'}"
Ankit Singh
  • 24,525
  • 11
  • 66
  • 89
0

You could use this valid expression:

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

As a matter of fact, url isn't a method but something specific to CSS that needs to be present in the final string.

Thierry Templier
  • 198,364
  • 44
  • 396
  • 360