【问题标题】:Angular 2+ disabling button of a particular row特定行的Angular 2+禁用按钮
【发布时间】:2019-04-07 03:32:26
【问题描述】:

我试图在单击添加按钮后禁用该按钮。 为简单起见,我不会仅添加导致问题的代码的详细信息。

<div *ngFor="let n of records">
   <span>{{n.name}}</span>
   <span>{{n.location}}</span>
   <button (click)="addtomainrecord(n)" [disabled]="disablebutton">add</button>
</div>

在我的组件中我已经声明了

  disablebutton:boolean=false;
   //later in my code
  addtomainrecord(record) {
     this.disablebutton=true;
   //rest of the code follows
  }

我面临的问题是,一旦我第一次单击添加按钮,所有按钮都被禁用,而我只想禁用我刚刚单击的行的按钮。

如何解决?

【问题讨论】:

    标签: javascript html angular button disable


    【解决方案1】:

    您可以为数组的每个项目添加一个新属性并检查此属性是否禁用项目:

    组件.ts

    myArray:Array<{firstName:string,lastName}>=[]; // there isn't isDisabled in this model
    
    doSomething(item){
       item.isDisabled=true;
       // do something
    }
    

    组件.html:

    <div *ngFor="let item of myArray">
       <button (click)="doSomething(item)" [disabled]="item.isDisabled">Register</button>
    </div>
    

    希望对你有帮助。

    【讨论】:

      【解决方案2】:

      如果您拥有records 数组的“所有权”,您可以添加另一个键值对,例如“禁用”,否则您可以创建一个与记录长度相同的并行数组disablebutton

        disablebutton = [false,false,...] // better be done in a for loop or with array methods in your code
      

      在模板中,您应该传递需要禁用按钮的行的 ID。您在 ngFor 中获得行索引:

      <div *ngFor="let n of records; let i = index">
         <span>{{n.name}}</span>
         <span>{{n.location}}</span>
         <button (click)="addtomainrecord(i)" [disabled]="disablebutton[i]">add</button>
      </div>
      

      并且该方法将捕获该索引以设置按钮状态:

        addtomainrecord(index) {
          this.disablebutton[index] = true;
        }
      

      Demo

      【讨论】:

      • 如果您需要更多关于在记录中创建和使用键值对的详细信息,请评论我:)
      • 感谢您使用您的解决方案使其正常工作。您的所有解决方案看起来都不错,无需更改我的对象。
      【解决方案3】:

      我希望它会起作用

      <div *ngFor="let n of records">
         <span>{{n.name}}</span>
         <span>{{n.location}}</span>
         <button (click)="addtomainrecord(n)" [disabled]="n.disablebutton">add</button>
      </div>
      
      
      addtomainrecord(record) {,
           record.disablebutton=true;
         //rest of the code follows
      }
      

      供参考:Disable button with ngFor

      【讨论】:

        猜你喜欢
        • 2017-10-14
        • 2016-09-14
        • 1970-01-01
        • 2017-10-05
        • 2021-04-16
        • 1970-01-01
        • 2015-09-08
        • 2023-03-12
        • 1970-01-01
        相关资源
        最近更新 更多