首页 > 解决方案 > Angular 风格:动态添加带有叠加层的背景图像

问题描述

所以我有一个包含图像文件名称的数组。我使用 Angular,这个数组是我的组件类的一个属性。

const backgroundImages = [
  'gym-background.jpg',
'home-background-2.jpg',
  'pt-background.jpeg'
];

我想将这些图像用作卡片的背景图像。我使用 Angular 并在我的模板中有以下代码

<div class="card" [style.background-image]="determineBackground()">
  <div class="card-header">
    <h3 class="card-title">{{workout.name}}</h3>
    <fa-icon class="card-enlarge" [icon]="['fas', 'search-plus']"></fa-icon>
  </div>
</div>

如您所见,这将触发组件中的确定背景()。此函数返回以下字符串:

  determineBackground() {
    const chosenImage = this.backgroundImgs[Math.floor(Math.random() * this.backgroundImgs.length)];

    return `linear-gradient(to bottom right, rgba(#000,.5), rgba(#000,.5)), url("/assets/images/${chosenImage}")`;
  }

所以,我返回background-imagestyle 属性的值。Math.floor(Math.random() * this.backgroundImgs.length)返回一个介于 0 和 2 之间的值,以随机决定将哪个图像用作背景。不幸的是,它不能以这种方式工作,即使 const selectedImage 是一个有效值,我也看不到背景图像。大家能帮我看看为什么吗?

完整的组件 ts 文件

@Component({
  selector: 'workout-list-item',
  templateUrl: './workout-list-item.component.html',
  styleUrls: ['./workout-list-item.component.scss']
})
export class WorkoutListItemComponent implements OnInit {

  backgroundImgs =  ['gym-background.jpg','home-background-2.jpg','pt-background.jpeg'];

  constructor(private router: Router) { }

  ngOnInit() { }

  determineBackground() {
    const chosenImage = this.backgroundImgs[Math.floor(Math.random() * this.backgroundImgs.length)];
return `linear-gradient(to bottom right, rgba(#000,.5), rgba(#000,.5)), url("/assets/images/${chosenImage}")`;
 }
}

更新代码

零件

export class WorkoutListItemComponent implements OnInit {

  backgroundImgs = backgroundImages;
  chosenImage: string;

  constructor(private router: Router) { }

  ngOnInit() {
    this.clientId = localStorage.getItem('userId');
    this.chosenImage = this.backgroundImgs[Math.floor(Math.random() * this.backgroundImgs.length)];
    console.log('choseImage', this.chosenImage);
  }
}

模板

<div
  class="card"
  [ngStyle]="{'background-image': chosenImage ? 'linear-gradient(to bottom right, rgba(#000,.5), rgba(#000,.5)), url(\'/assets/images/' + chosenImage + '\')' : ''}"
>
  <div class="card-header">
    <h3 class="card-title">{{workout.name}}</h3>
    <fa-icon class="card-enlarge" [icon]="['fas', 'search-plus']"></fa-icon>
  </div>
</div>

标签: javascriptcssangularsass

解决方案


继续我的评论:从模板调用函数将导致更改检测器循环遍历函数数十次 - 使用ngOnInitorngAfterViewInit并在组件上设置公共属性,然后绑定到该组件

在模板中使用以下ngStyle方法可以轻松避免url消毒问题

[ngStyle]="{
                'background-image': (chosenImage) ? 'url(' + chosenImage + ')' : ''         
            }"

推荐阅读