簡體   English   中英

角度樣式:動態添加帶有疊加層的背景圖像

[英]Angular style: add dynamically a background-image with an overlay

所以我有一個包含圖像文件名稱的數組。 我使用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>

如您所見,這將觸發組件中的defineBackground()。 該函數返回以下字符串:

  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>

按照我的評論進行操作:從模板調用函數將使變更檢測器多次遍歷該函數-使用ngOnInitngAfterViewInit並在組件上設置一個公共屬性,然后綁定到該組件

在模板中使用以下ngStyle方法可以避免url清理問題,而不會麻煩

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM