Angular 中背景图像 url 的属性 属性 绑定 2

Attribute property binding for background-image url in Angular 2

我一直在努力寻找动态更改多个 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; }
  }

我认为问题不在于 observable,因为 username 显示并执行 <img *ngIf="image" src="{{ image }}"> 之类的操作来渲染图像。我必须访问 background-image 属性,因为显然这是制作圆形图像的最佳方式,但通常想知道如何执行此操作。

编辑:

我原来的 [ngStyle] 声明有不必要的大括号(ngStyle 是一个可以接受变量的指令),并且缺少 url()image 周围的字符串标记。正确的方法(如下所述)是:

<div class="profile-image" [ngStyle]="{'background-image': 'url(' + image + ')'}"></div>`.

正如原始编辑中所述,也可以使用Angular中的Renderer class 2.我有尚未这样做,但认为应该有 setElementStyles 或类似的方法。我会尝试 post 举个例子,但如果有人暂时向我(和其他人)展示如何操作,我会很高兴。

我认为你应该使用类似的东西:

<div class="profile-image"
     [ngStyle]="{ 'background-image': 'url(' + image + ')'}">

其中 image 是您组件的 属性。

看到这个问题:

您不需要使用 NgStyle。您也可以这样做:

[style.background-image]="'url(' + image + ')'"

查看更多

错了

我认为你应该补充:

<div class="profile-image" [ngStyle]="{ 'backgroundImage': url({{image}})">

此致

主要原因很简单,你将一个全局变量声明为blankImage,但在模板中你调用了image而不是blankImage

你的ts代码变量blankImage

blankImage: string = '../assets/.../camera.png';

你的模板代码变量image

<div class="profile-image" [ngStyle]="{'background-image': 'url(' + image + ')'}"></div>

效果很好,因为图像 URL 中没有 space,但通过稍微更改代码,我们可以使其再次起作用:

<div style.background-image="url('{{image}}')"></div>"