使用打字稿更改喜欢按钮的颜色

时间:2021-05-31 09:48:05

标签: angular 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>

打字稿

 @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,即使当前用户喜欢该帖子。我从后端发送喜欢的列表,我的 Like 类包含一个 id、一个帖子 id 和一个用户 id。这就是 this.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)

1 个答案:

答案 0 :(得分:0)

我不是 Angular 高手,但对我来说,您似乎以错误的方式访问按钮。

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

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');
   }
}
相关问题