css - Attribute property binding for background-image url in Angular 2 -
i have been struggling figure out best way dynamically change background-image
attribute in number of angular 2 components.
in following example, attempting set background-image
of div @input
value using [ngstyle]
directive:
import {component, input} '@angular/core'; import { user } '../models'; // exporting type aliases enforce better type safety (https://github.com/ngrx/example-app) export type userinput = user; @component({ selector: 'profile-sidenav', styles: [ ` .profile-image { background-repeat: no-repeat; background-position: 50%; border-radius: 50%; width: 100px; height: 100px; } `], template: ` <div class="profile-image" [ngstyle]="{ 'background-image': url({{image}})"> <h3>{{ username }}</h3> ` }) export class profilesidenav { @input() user: userinput; blankimage: string = '../assets/.../camera.png'; // utilizing "getters" keep templates clean in 'dumb' components (https://github.com/ngrx/example-app) username() { return this.user.username; } image() { if (!this.user.image) { return this.cameraimage; } else { return this.user.image; } }
i don't think issue observable, since username
displays , doing <img *ngif="image" src="{{ image }}">
renders image. have access backgroung-image
attribute because apparently best way make circular image, in general know how this.
edit:
my original [ngstyle]
declaration had unnecessary curly brackets (ngstyle directive can take variable), , missing string tags around url()
, image
. correct way (as answered below) is:
<div class="profile-image" [ngstyle]="{'background-image': 'url(' + image + ')'}"></div>`.
as stated in original edit, solution can achieved renderer class in angular 2. have yet it, think there should way setelementstyles
or that. try post example, love if else showed me (and others) how time being.
i think should use that:
<div class="profile-image" [ngstyle]="{ 'background-image': 'url(' + image + ')'}">
where image
property of component.
see question: