javascript - 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-image
style 属性的值。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>
解决方案
继续我的评论:从模板调用函数将导致更改检测器循环遍历函数数十次 - 使用ngOnInit
orngAfterViewInit
并在组件上设置公共属性,然后绑定到该组件
在模板中使用以下ngStyle
方法可以轻松避免url
消毒问题
[ngStyle]="{
'background-image': (chosenImage) ? 'url(' + chosenImage + ')' : ''
}"
推荐阅读
- angularjs - AngularJS Ng-Repeat不在数组中显示数据
- c++ - 为什么堆栈展开后程序无法到达正确的返回指令?
- javascript - React 复选框控制组件
- opengl - ShadowMap 渲染的阴影计算问题
- javascript - Javascript Jquery 滚动偏移量
- django - 使用模型中的 get_initial() 在 CreateView 中填充表单数据
- linux - base64解码后执行
- elixir - 在 Elixir 中,为什么我的寻找素因数的算法一旦达到数字 33 就会变得奇怪,我该如何解决?
- python - 删除以重复符号结尾的字符串 (Python)
- arrays - PowerShell:将对象的 ArrayList 作为参数传递到另一个脚本中