javascript - 以 ngIf 为条件禁用/启用 ngFor 内的多个按钮

标签 javascript html angular typescript button

我有一个按钮列表,需要根据条件启用/禁用,一次可能会禁用两个或三个按钮。

<li *ngFor="let button of buttons; let i = index">
   <button *ngIf="disableButtonIndex  && i+1 == disableButtonIndex" class="btn btn-lg btn-primary" disabled> {{ button.title }}</button>
   <button *ngIf="!(disableButtonIndex  && i+1 == disableButtonIndex)" (click)="callAction(button.actionName || i)" class="btn btn-lg btn-primary">{{ button.title }}</button>
</li>

.ts

this.disableButtonIndex = 1;

上面的代码可以很好地禁用单个按钮,我如何禁用两个/更多按钮

最佳答案

您可以使用数组来保存禁用的索引或在按钮选项中添加禁用标志。

使用禁用的数组

https://stackblitz.com/edit/angular-sef3nc?file=src%2Fapp%2Fapp.component.html

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  disabledButtons= [1, 2]

  buttons = [
    {
      actionName: 'action1',
      title: 'button1'
    },
    {
      actionName: 'action2',
      title: 'button2'
    },
    {
      actionName: 'action3',
      title: 'button3'
    }
  ]

  callAction(action) {
    console.log(action)
  }
}
<li *ngFor="let button of buttons; let i = index">
   <button class="btn btn-lg btn-primary" 
           [disabled]="disabledButtons.indexOf(i) !== -1"
           (click)="callAction(button.actionName)"> 
           {{ button.title }}
   </button>
</li>

在选项中使用标志

https://stackblitz.com/edit/angular-zvbepr?file=src%2Fapp%2Fapp.component.html

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  buttons = [
    {
      actionName: 'action1',
      title: 'button1',
      disabled: true
    },
    {
      actionName: 'action2',
      title: 'button2',
      disabled: true
    },
    {
      actionName: 'action3',
      title: 'button3',
      disabled: false
    }
  ]

  callAction(action) {
    console.log(action)
  }
}
<li *ngFor="let button of buttons; let i = index">
   <button class="btn btn-lg btn-primary" 
           [disabled]="button.disabled"
           (click)="callAction(button.actionName)"> 
           {{ button.title }}
   </button>
</li>

关于javascript - 以 ngIf 为条件禁用/启用 ngFor 内的多个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60824359/

相关文章:

javascript - 无法从下拉数据列表 JS/HTML 获取值

javascript - 防止 IE11 在 Angular 2 中缓存 GET 调用

css - 当其容器/父元素悬停时将 css 样式应用于元素 Angular

angular - 捕获包装到可观察对象中的 promise 错误 - angular 2

javascript - 在 React 应用程序中显示 SVG 时出现问题

javascript - 如何选择加载的图像并将其插入到 div 中

Javascript onclick 自动触发

javascript - JS 输出到 html 输入

javascript - 如何将背景轮播图片变小

PHP MySQL 和表单,没有任何反应