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

时间:2019-05-02 11:22:40

标签: javascript html angular

我正在尝试禁用已登录用户投票的按钮,但是,当我在ngFor(在下面的示例中)中使用disabled指令时,所有按钮都被禁用,而不仅仅是包含已登录按钮的项目在用户中。我的目标是检查数组是否包含当前用户的uid,如果禁用,则禁用按钮。我该如何实现?预先感谢

compontent.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"获得了预期的结果。感谢先生的帮助。

1 个答案:

答案 0 :(得分:1)

最好的方法是将[submodule "tanuki/awesome_project"] path = tanuki/awesome_project url = https://<username>:<deploy_token>@gitlab.example.com/tanuki/awesome_project.git 作为disabledButton数组中property的{​​{1}}的一部分, 然后item上的items应该是[disabled]

然后您可以通过简单地识别用户并将其相应的button [disabled]="item.disabledButton"属性设置为disabled来控制item's,从而控制应该是disabledButton < / p>