pingo pingo - 6 months ago 745
AngularJS Question

Attribute property binding for background-image url in Angular 2

I have been struggling to figure out the best way to dynamically change the

background-image
attribute in a number of Angular 2 components.

In the following example, I am attempting to set the
background-image
of a div to an
@Input
value using
[ngStyle]
directive:

import {Component, Input} from '@angular/core';
import { User } from '../models';

// exporting type aliases to 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" to keep templates clean in 'dumb' components (https://github.com/ngrx/example-app)
get username() {
return this.user.username;
}
get image() {
if (!this.user.image) { return this.cameraImage;
} else { return this.user.image; }
}


I don't think the issue is with the observable, since
username
displays and doing something like
<img *ngIf="image" src="{{ image }}">
renders the image. I have to access the
backgroung-image
attribute because apparently that is the best way to make a circular image, but in general would like to know how to do this.

It would be easy if I could pass a variable into the component's stylesheet, but I don't think that is supported. I am attempting to right the style inline, but it doesn't seem to be working. Do I need to make a separate attribute directive and import that into the file? Or is there a way to do this all in one component?

Also, I have explored using the Renderer class to do something like
setElementStyles
, but I am not sure if that's the best approach.

Any advice on how to do this (with attribute/property directives and inline html or the renderer class) would be greatly appreciated.

I have another instance where I need to cycle through a few background-image url's on the root component, but this seems like an easier example to tackle for now. Thank you!

Answer

I think that you should use something like that:

<div class="profile-image"
     [ngStyle]="{ 'background-image': 'url(' + image + ')'}">

where image is a property of your component.

See this question:

Comments