简体   繁体   中英

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.

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"

or sommething similar. There is possible to pass function, not only variable in [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"

<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}">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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