【问题标题】:Change color of like button using typescript使用打字稿更改喜欢按钮的颜色
【发布时间】:2021-05-31 18:16:56
【问题描述】:

我创建了一个包含帖子列表的应用,用户可以喜欢/不喜欢帖子。对于类似的功能,我使用了 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,如果有,like 按钮必须是红色的。

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 typescript


    【解决方案1】:

    我不是 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');
       }
    }
    

    【讨论】:

    • 但即使我使用第一个或第二个选项,我也无法再应用样式了。
    猜你喜欢
    • 2019-11-27
    • 2019-11-19
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-21
    • 2012-09-20
    相关资源
    最近更新 更多