I'm new to Angular, working on my first app in Angular 8 and I want to toggle a component css class based on an objects array values.
The object is a post (test-data/posts.ts) with an array of likes
export const posts = [{
id: 1,
author: {},
type: 'image',
media: '',
repost: 0,
comments: [],
likes: [ 1, 2, 3, 4]
}];
So my component typescript is this, to add and remove a like on the post, this is working
import { Component } from '@angular/core';
import { user } from '../test-data/user';
import { posts } from '../test-data/posts';
@Component({
selector: 'app-feed',
templateUrl: './feed.component.html',
styleUrls: ['./feed.component.css'],
})
export class FeedComponent {
posts = posts;
user = user;
liked = false;
likePost(post) {
// If post is liked, remove like
if (this.isLiked(post)) {
for (let i = 0; i < post.likes.length; i++) {
if (post.likes[i] === user.id) { post.likes.splice(i, 1); }
}
// If not liked add a new like
} else {
post.likes.push(user.id);
}
// DEBUG: Log post data
console.log(post);
}
isLiked(post) {
return post.likes.includes(user.id);
}
}
I can retrieve the object, add/remove likes with the component, but how do I check the array to determine is the post should display as liked or unliked?
My current html template is this, I'd like the to have an extra class "feed-icon-red" if the user id (user.id) appears in the posts like array (post.likes)
<div *ngIf="posts.length">
<div *ngFor="let post of posts">
<mat-list>
<!-- Post Media -->
<img class="feed-image" [src]="post.media" (dblclick)="likePost(post)"/>
<!-- Interaction Button Row -->
<mat-list-item>
<span>
<mat-icon mat-list-icon class="ti-heart" [class.feed-icon-red]="" (dblclick)="likePost(post)"></mat-icon>
</span>
</mat-list-item>
</mat-list>
</div>
</div>
EDIT: I'd like to check for a specific value within the array to set the class. e.g. if (post.likes.includes(1)) set the icon class to 'feed-icon-red'