我一直在努力找出在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>`.

正如最初编辑中的stated,Angular 2中的Renderer类也可以实现解决方案.我还没有做到这一点,但我认为应该有一种方法来解决这个问题.我将try 发布一个例子,但如果有人向我(和其他人)展示如何暂时做到这一点,我会很高兴.

推荐答案

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

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

其中image是组件的属性.

请看这个问题:

Typescript相关问答推荐

如何将单元测试中的私有订阅变量设置为空(或未定义)?

TS 2339:属性切片不存在于类型DeliverableSignal产品[]上>'

React Hook中基于动态收件箱定义和断言回报类型

如何创建泛型类型组件来使用React Native的FlatList或SectionList?'

在配置对象上映射时,类型脚本不正确地推断函数参数

返回同时具有固定键和变量键的对象的函数的返回类型

带占位符的模板文字类型何时扩展另一个?

状态更新后未触发特定元素的Reaction CSS转换

无法正确推断嵌套泛型?

参数属性类型定义的REACT-RUTER-DOM中的加载器属性错误

限制返回联合的TS函数的返回类型

将接口映射到交叉口类型

如何在不违反挂钩规则的情况下动态更改显示内容(带有状态)?

是否可以在类型脚本中定义条件返回类型,而不在函数体中使用类型转换?

字幕子集一个元组的多个元素

TS不能自己推断函数返回类型

有没有一种方法可以防止我的组件包在其中安装样式组件'; node 模块中的s目录

如何使用useSearchParams保持状态

为什么过滤器不改变可能的类型?

基于参数的 TS 返回类型