disable buttons in ngFor loop

爱⌒轻易说出口 提交于 2019-12-25 00:08:14

问题


I want to disable buttons inside by ngFor loop.I set the i-index inside ngFor but the issue is that it only disables the button with the id of i.If i want to disable multiple buttons inside this loop what should i do?

Lets say i have 5 buttons.I want to disable the button number 1.After i want to disable 2.With this code when i change to 2 the 1 goes back to enable.

<div *ngFor="let day of days let i=index">
    <ion-button id={{day}} expand="block" size="large" (click)="test(day)" ngDefaultControl [(ngModel)]="days" [disabled]="i==dayFinished" >DAY {{day}}</ion-button>
</div>

And in the .ts file :

   dayFinished = null;
   this.dayFinished = this.route.snapshot.paramMap.get("id");
   this.dayFinished -= 1;

回答1:


if you want to disable days that you have clicked then

html

<div *ngFor="let day of days let i=index">
    <ion-button id={{day}} expand="block" size="large" (click)="test(day)" ngDefaultControl [(ngModel)]="days" [disabled]="checkIfFinnished(day)" >DAY {{day}}</ion-button>
 </div>

In component.ts file

   dayFinished = [];

   this.dayFinished.push(this.route.snapshot.paramMap.get("id"));


  test(day){
   if(this.dayFinished.includes(day)){
      this.dayFinished.splice(this.dayFinished.indexOf(day),1);
   }
   else
   { 
    this.dayFinished.push(day);
   }
  }

  checkIfFinnished(item){
     return  this.dayFinished.includes(item);
   }



回答2:


You can use an array of object like this [{day: 1, disabled: true}, {day: 2, disabled: false}], then you use the property 'disabled' for the accessibility and the 'day' to display You do the logic for the true/false in the component

<div *ngFor="let item of objectArray let i=index">
    <ion-button id={{item.day}} expand="block" size="large" (click)="test(item.day)" ngDefaultControl [(ngModel)]="days" [disabled]="item.disabled" >DAY {{item.day}}</ion-button>



来源:https://stackoverflow.com/questions/55494515/disable-buttons-in-ngfor-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!