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

pin*_*ngo 27 css typescript angular-directive angular

我一直在努力找出background-image在许多Angular 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; }
  }
Run Code Online (Sandbox Code Playgroud)

我认为问题不在于观察,因为username显示和做一些事情就像<img *ngIf="image" src="{{ image }}">呈现图像一样.我必须访问该background-image属性,因为显然这是制作圆形图像的最佳方式,但通常想知道如何做到这一点.

编辑:

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

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

至于在原来的编辑,一个解决方案也可以与实现渲染的角度2.我还没有做到这一点,但认为应该有一个办法类setElementStyles或类似的东西.我会尝试发布一个例子,但如果有人向我(和其他人)展示如何暂时如愿,我会很高兴.

Thi*_*ier 54

我认为你应该使用这样的东西:

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

哪里image是您组件的属性.

看到这个问题:

  • Nvm,让它发挥作用.我引用的`blankImage`在路径中有一些空格,因此导致了问题. (2认同)

red*_*x05 23

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

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

请参阅如何使用ngStyle(angular2)添加背景图像?