我一直在努力找出在许多 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>`.
如原始编辑中 所述,也可以使用 Angular 2 中的 Renderer 类来实现解决方案。我还没有这样做,但认为应该有一种方法 setElementStyles
或类似的东西。我将尝试发布一个示例,但如果其他人暂时向我(和其他人)展示如何操作,我会很高兴。
原文由 0xPingo 发布,翻译遵循 CC BY-SA 4.0 许可协议
我认为你应该使用类似的东西:
其中
image
是组件的属性。看到这个问题: