javascript - 在 Angular 7 的 ngFor 中有条件地禁用按钮

标签 javascript html angular

我试图禁用已登录用户投票的按钮,但是,当我在 ngFor 中使用 disabled 指令时(在下面的示例中),所有按钮都被禁用,而不仅仅是包含已登录用户的项目在用户。我的目标是检查数组是否包含当前用户的 uid,如果包含则禁用该按钮。我怎样才能做到这一点?提前致谢

组件.ts:

this.itemsCollection = this.afs.collection('food', ref => ref.orderBy('voteCount', 'desc'));
          this.items = this.itemsCollection.snapshotChanges().pipe(
            map(actions => actions.map(a => {
              const data = a.payload.doc.data();
              const id = a.payload.doc.id;
                  this.afAuth.authState.subscribe(user => {
                    if(user) {
                       this.user = user.uid;
                        if (data.votedBy.includes(user.uid)){
                         console.log(id);
                         console.log('you already voted');
                         this.disabledButton = true;
                         return false;
                              }
                    else {
                        this.disabledButton = false;
                         }
                }
                });
              return { id, ...data };
            }))
          );

HTML:

<div class="firestoreLoop" *ngFor="let item of items | async" >
        <div class="container1">
            <div class="card">
                <div class="card-body">
                <p>{{item.voteCount}}</p>
                <p>{{item.id}}</p>
                <p>{{item.votedBy}}</p>
                <p>{{user}}</p>
                </div>
            <button type="button" id="item.id" class="btn"(click)="upvote(item.id)" [disabled]="disabledButton">Upvote</button>
            </div>
        </div>
    </div>

编辑:我通过向按钮添加 *ngIf= "user != item.votedBy" 得到了想要的结果。感谢先生的帮助。

最佳答案

最好的方法是将 disabledButton 添加为 items 数组中 itemproperty, 然后 button 上的 [disabled] 应该是 [disabled]="item.disabledButton"

然后您可以通过简单地识别用户并将其相应的 item disabledButton 属性设置为 来控制应该禁用的项目真 否则

关于javascript - 在 Angular 7 的 ngFor 中有条件地禁用按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55951365/

相关文章:

javascript - 我无法在 Meteor 应用程序中使用聊天功能

angular - 如何使用 switchMap 取消挂起的 http 请求并只接受最后一次订阅?

angular - 将 Angular 2 应用程序部署到 github 页面 - 失败

javascript - 使用 JavaScript 创建菜单树?

javascript - lodash 基于属性的唯一性

html - 当浏览器宽度改变时图像在 ie8 中不调整大小

javascript - 过滤器抛出 - 无法读取 null 的属性 'toLowerCase'

javascript - 如何在 ngDialog 中加载数据

javascript - 如何将参数从 gulp 观察者传递给任务

javascript - 如何让我的导航栏出现在某个部分?