2

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

<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
  }

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

如何修复?

4

3 回答 3

5

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

组件.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>

我希望这可以帮助你。

于 2019-04-07T04:02:19.813 回答
2

我希望它会工作

<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
}

供参考:使用 ngFor 禁用按钮

于 2019-04-07T03:43:35.223 回答
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;
  }

演示

于 2019-04-07T04:45:59.990 回答