【发布时间】:2019-11-29 07:25:22
【问题描述】:
所以我有一个包含图像文件名称的数组。我使用 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()。此函数返回以下字符串:
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 样式属性的值。 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>
【问题讨论】:
-
检查错误日志,你应该有一些关于消毒的内容
-
该 CSS 格式不正确 - 您是否在 Angular 之外对其进行了测试?你不应该从模板中调用函数——它会循环函数几十次——使用
ngOnInit并在组件上设置一个公共属性,然后绑定到那个 -
@Drenai 是的,我改变了它,现在 HTML 是:
-
仍然没有背景图像,但就像@Vega 说的那样,我确实收到了清理错误。
-
感谢 Vega,不胜感激。
标签: javascript css angular sass