使用typescript更改类似按钮的颜色



我创建了一个带有帖子列表的应用程序,用户可以喜欢/不喜欢帖子。对于点赞功能,我使用了SignalR,一切都很好,但如果登录的用户已经喜欢某个帖子,我想更改点赞按钮的颜色,这样他就知道自己喜欢哪些帖子了。我试过这样做:Html

<button id="like" (click)="liked(post)" class="btn liked mr-5">Like<em class="fa fa-thumbs-up"></em> {{post.likes.length}}</button>

TypeScript

@Input() post: Post;
button = document.getElementById('like')
constructor(private postService: PostsService)
liked(post: Post) {
const user: User = JSON.parse(localStorage.getItem('user'));
const id = this.getDecodedToken(user.token).nameid;
if(this.post.likes.includes(parseInt(id))) {
this.button.style.color = "red"
}
this.postService.setLike(parseInt(id), post.id);
}

这不起作用。我在控制台中收到一个错误,说TypeError: Cannot read property 'style' of nullthis.post.likes.includes(parseInt(id))返回false,即使当前用户喜欢这个帖子。我从后端发送点赞列表,我的点赞类包含一个id、一个帖子id和一个用户id。这就是这个.post.likes在控制台中的显示方式,基本上我想做的是验证当前用户的id是18还是5,如果是,点赞按钮必须是红色的。

0: {id: 13, created: "0001-01-01T00:00:00", user: null, userId: 18, post: null, …}
1: {id: 1026, created: "2021-05-22T12:46:02.811552", user: null, userId: 5, post: null, …}
length: 2
__proto__: Array(0)

我不是Angular master,但对我来说,你似乎以错误的方式访问了按钮。

你应该使用其中一个(最好是第一个选项(

export class AppComponent implements AfterViewInit {
@ViewChild('like') likeButton: ElementRef;
ngAfterViewInit() {
console.log(this.likeButton.nativeElement.innerHTML);
}
}

或者像这个一样将文档注入组件

import { Inject }  from '@angular/core';
import { DOCUMENT } from '@angular/common'; 
@Component({...})
export class AppComponent {
likeButton: any;
constructor(@Inject(DOCUMENT) document) {
likeButton = document.getElementById('el');
}
}

最新更新