Angular 2中背景图像URL的属性属性绑定 [英] Attribute property binding for background-image url in Angular 2
问题描述
我一直在努力寻找在许多 Angular 2 组件中动态更改background-image
属性的最佳方法.
I have been struggling to figure out the best way to dynamically change the background-image
attribute in a number of Angular 2 components.
在下面的示例中,我尝试使用[ngStyle]
指令将div的background-image
设置为@Input
值:
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; }
}
我认为问题不是可观察到的,因为显示username
并执行类似<img *ngIf="image" src="{{ image }}">
的操作会渲染图像.我必须访问background-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 background-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.
我最初的[ngStyle]
声明有不必要的花括号(ngStyle是可以接受变量的指令),并且缺少url()
和image
周围的字符串标签.正确的方法是(如下所述):
My original [ngStyle]
declaration had unnecessary curly brackets (ngStyle is a directive that can take a variable), and was missing string tags around url()
and image
. The correct way is (as answered below) is:
<div class="profile-image" [ngStyle]="{'background-image': 'url(' + image + ')'}"></div>`.
As stated in the original edit, a solution can also be achieved with the Renderer class in Angular 2. I have yet to do it but think there should be a way with setElementStyles
or something like that. I will try to post an example but would love if someone else showed me (and others) how to for the time being.
推荐答案
我认为您应该使用类似的东西:
I think that you should use something like that:
<div class="profile-image"
[ngStyle]="{ 'background-image': 'url(' + image + ')'}">
其中image
是组件的属性.
看到这个问题:
这篇关于Angular 2中背景图像URL的属性属性绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!