【发布时间】:2016-10-01 08:00:57
【问题描述】:
我一直在努力找出在许多 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 的方法或类似的东西。我会尝试发布一个示例,但如果其他人暂时向我(和其他人)展示如何操作,我会很高兴。
【问题讨论】:
标签: css angular typescript angular-directive