我一直在努力找出动态地改变background-image
属性在多个角2个组件的最佳途径。
在下面的例子中,我试图用background-image
指令一个div的@Input
设置为一个[ngStyle]
值:
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>`.
正如原编辑表示,解决方案也可以在转角2.我还没有做到这一点,但认为应该有与Rendereror类似的东西的方式setElementStyles
类实现。我会尝试发布一个例子,但会很喜欢,如果别人给我(和其他人)如何暂时。
我认为你应该使用类似的东西:
<div class="profile-image"
[ngStyle]="{ 'background-image': 'url(' + image + ')'}">
其中image
是组件的属性。
看到这个问题:
你并不需要使用NgStyle。你也可以这样做:
[style.background-image]="'url(' + image + ')'"
最主要的原因是很简单的,你声明的全局变量blankImage但在模板中键入图像。这就是两种不同的变量
您的TS码**blankImage**: string = '../assets/.../camera.png';
模板代码**<div class="profile-image" [ngStyle]="{'background-image': 'url(' + **image** + ')'}"></div>
.`
只是将图像改变为空白图像,或反之亦然
这是错误的
我想你应该加上:
<div class="profile-image" [ngStyle]="{ 'backgroundImage': url({{image}})">
问候