我一直在努力找出在Angular 2个组件中动态更改background-image
属性的最佳方法.
在下面的示例中,我试图使用[ngStyle]
指令将div的background-image
设置为@Input
值:
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
属性,因为这显然是制作圆形图像的最佳方法,但通常我想知道如何做到这一点.
编辑:
我最初的[ngStyle]
声明有不必要的花括号(ngStyle是一个可以接受变量的指令),并且缺少url()
和image
左右的字符串标记.正确的方法是(如下所示):
<div class="profile-image" [ngStyle]="{'background-image': 'url(' + image + ')'}"></div>`.
正如最初编辑中的stated,Angular 2中的Renderer类也可以实现解决方案.我还没有做到这一点,但我认为应该有一种方法来解决这个问题.我将try 发布一个例子,但如果有人向我(和其他人)展示如何暂时做到这一点,我会很高兴.