简体   繁体   English

在 Angular 中禁用 ngFor 中的一个按钮

[英]Disable one button in ngFor in Angular

I have an add to list button in my component, that disables when a user clicks it once.我的组件中有一个添加到列表按钮,当用户单击它一次时会禁用该按钮。 Problem is when the user clicks the button next to the list item they want to add, it disable all the other list buttons also?问题是当用户单击他们想要添加的列表项旁边的按钮时,它也会禁用所有其他列表按钮吗? I only want it to disable the one selected.我只希望它禁用所选的那个。 My code so far is:到目前为止我的代码是:

component.html组件.html

<div *ngFor="let itunes of data | paginate: { itemsPerPage: 10, currentPage: p } | filter:filter; let i = index">
    <div class="row">
      <div class="col-lg-2 col-md-2 col-sm-12">
        <img class="align-self-start mr-5 mb-5 artwork" src="{{itunes.artworkUrl100}}" alt="image">
      </div>
      <div class="col-md-8 col-lg-8 col-sm-12">
        <h2 class="mt-0 d-inline-block text-truncate trunc">{{itunes.collectionName}}</h2>
        <h4 class="mt-0 mb-3">{{itunes.artistName}}</h4>
        <h5 class="mt-0 mb-3"><a href="{{itunes.collectionViewUrl}}" target="_blank">Listen</a></h5>
      </div>
      <div class="col-md-2 mb-5 col-lg-2 col-sm-12">
        <a target="_blank"><button type="button" class="btn btn-primary btn-lg float-right"
            (click)="addSongToPlaylist(itunes); clicked = true;" [disabled]="clicked">
            <fa-icon [icon]="faPlus">
            </fa-icon>
          </button></a>
      </div>
    </div>
  </div>

component.ts (Add function) component.ts (添加功能)

  addSongToPlaylist(itunes) {
    this.list.playlist.push(Object.assign({}, itunes));
    this.list.savePlaylist();
    console.log('Playlist - ', this.list.playlist);
  }

Any ideas, what I am doing wrong?任何想法,我做错了什么?

You have only one clicked property and all buttons have their disabled property bound to that property.您只有一个clicked属性,并且所有按钮都将其disabled属性绑定到该属性。 That is why they are all enabled or disabled at the same time.这就是为什么它们都同时启用或禁用的原因。

The simplest solution is to add a clicked property to the Itunes class, and modify its value when the button is clicked:最简单的解决方法是在Itunes类中添加一个clicked属性,并在按钮被点击时修改其值:

(click)="addSongToPlaylist(itunes); itunes.clicked = true;" [disabled]="itunes.clicked"

An alternative is to store the clicked value in a separate array, where each array item refers to an item of the data array.另一种方法是将clicked值存储在单独的数组中,其中每个数组项都引用数据数组中的一项。

Maybe do this:也许这样做:

<button type="button" class="btn btn-primary btn-lg float-right"
            (click)="addSongToPlaylist(itunes); clicked = i;" [disabled]="clicked===i">
            <fa-icon [icon]="faPlus">
            </fa-icon>
          </button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM