简体   繁体   English

根据某些条件添加类Angular2

[英]Add class based on some condition Angular2

I am working with ng2 project and I need a help with one task, where should I add css class, only for one item from array. 我正在使用ng2项目,我需要一项任务的帮助,我应该在哪里添加css类,仅适用于数组中的一项。

I got sommething like this: 我有点像这样:

<div class="ds-photo__item" *ngFor="let albumPhoto of albumPhotos">
  <div class="ds-photo__item--cover">
    <img class="ds-photo__item--cover-photo" [src]="albumPhoto.url" alt="" (click)="choseCover(albumPhoto)" [class.selected]="...">
  </div>
</div>

And I need add class select only for one item which is choosen by function below: 我只需要为以下功能选择的一项添加添加类选择:

selectCover() {
    if (this.album.cover) {
        this.cover = this.albumPhotos.find( photo => photo.id === this.album.cover );
        console.log("COVER: ", this.cover);
        this.isCover = true;
    } else { this.isCover = false }
}

after that, I have one object with current cover of album. 在那之后,我有了一个带有当前专辑封面的对象。 I need to add class "selected" to listed item, whuch is actualy cover. 我需要将“已选择”类别添加到列出的项目中,实际上是封面。

I need something like this: [class.selected]="if albumPhoto.id === cover.id" 我需要这样的东西:[class.selected] =“ if albumPhoto.id === cover.id”

or sommething similar. 或类似的东西。 There is possible to pass function, not only variable in [class.my-class] ? 可以传递函数,而不仅是[class.my-class]变量?

Please for hints! 请提示! Regards Greg 问候格雷格

您可以按以下方式使用ngClass

<img class="ds-photo__item--cover-photo" [src]="albumPhoto.url" alt="" (click)="choseCover(albumPhoto)" [ngClass]="{selected : albumPhoto.id === cover.id}">

Done with: 完成于:

[class.selected]="cover.id === albumPhoto.id"

I hope it will help someone. 希望对您有所帮助。

Bye! 再见!

If you need only one class to be applied based on some condition then use [class.selected]="cover.id === albumPhoto.id" 如果您只需要根据某个条件应用一个类,则使用[class.selected]="cover.id === albumPhoto.id"

<img class="ds-photo__item--cover-photo" [src]="albumPhoto.url" alt="" (click)="choseCover(albumPhoto)" [class.selected]="cover.id === albumPhoto.id">
[class.selected]="cover.id === albumPhoto.id"

but If you have multiple class to be applied based on some condition then just use this format 但是如果您要根据某些条件应用多个类,则只需使用此格式

[ngClass]="{selected : albumPhoto.id === cover.id}"

<img class="ds-photo__item--cover-photo" [src]="albumPhoto.url" alt="" (click)="choseCover(albumPhoto)" [ngClass]="{selected : albumPhoto.id === cover.id}">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM